jeudi 12 novembre 2015

How to remove repetitions in class methods?

I have RESTeasy service. And have implemented simple error handling on methods using try catch and feel something is not wery well with it. I've noticed try catch repetition on all my methods. So I want ask way how to avoid repetition (to reduce code size) of try catch but not lost functionality.

@Path("/rest")
@Logged
@Produces("application/json")
public class CounterRestService {

  @POST
  @Path("/create")
  public CounterResponce create(@QueryParam("name") String name) {
    try {
        CounterService.getInstance().put(name);
        return new CounterResponce();
    } catch (Exception e){
        return new CounterResponce("error", e.getMessage());
    }   
}

@POST
@Path("/insert")
public CounterResponce create(Counter counter) {
    try {
        CounterService.getInstance().put(counter);
        return new CounterResponce();
    } catch (Exception e){
        return new CounterResponce("error", e.getMessage());
    }
}

@DELETE
@Path("/delete")
public CounterResponce delete(@QueryParam("name") String name) {
    try {
        CounterService.getInstance().remove(name);
        return new CounterResponce();
    } catch (Exception e){
        return new CounterResponce("error", e.getMessage());
    }
}
... // other methods with some try catch pattern

responce

public class CounterResponce {
private String status;

@JsonSerialize(include=Inclusion.NON_NULL)
private Object data;

public CounterResponce() {
    this.status = "ok";
}

public CounterResponce(Object o) {
    this.status = "ok";
    this.data = o;
}

public CounterResponce(String status, Object o){
    this.status = status;
    this.data = o;
}

public String getStatus() {
    return status;
}
public void setStatus(String status) {
    this.status = status;
}
public Object getData() {
    return data;
}
public void setData(Object data) {
    this.data = data;
}
}

Aucun commentaire:

Enregistrer un commentaire