如何在类方法中删除try / catch重复? [英] How to remove try/catch repetitions in class methods?

查看:93
本文介绍了如何在类方法中删除try / catch重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有RESTeasy服务。并且使用 try catch 的方法实现了简单的错误处理,并感觉到它不是很好。我注意到尝试在所有方法上重复。所以我想要如何避免重复(减少代码大小) try catch 但不会丢失功能。

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

@POST
@Path(/ create)
public CounterResponce create(@QueryParam(name)String name){
try {
CounterService.getInstance( )。把(名称);
返回新的CounterResponce();
} catch(Exception e){
return new CounterResponce(error,e.getMessage());
}
}

@POST
@Path(/ insert)
public CounterResponce create(Counter counter){
try {
CounterService.getInstance()。put(counter);
返回新的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);
返回新的CounterResponce();
} catch(Exception e){
return new CounterResponce(error,e.getMessage());
}
}
... //其他一些尝试catch模式的方法

响应

  public class CounterResponce {
private String status;

@JsonSerialize(include = Inclusion.NON_NULL)
private对象数据;

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;
}
}

例外源

  public class CounterService {

private Map< String,StatisticCounter> counters = new HashMap< String,StatisticCounter>();

private static CounterService instance = null;

protected CounterService(){}

public static CounterService getInstance(){
if(instance == null){
instance = new CounterService );
}
return instance;
}

public StatisticCounter get(String name){
StatisticCounter c = counters.get(name);
if(c == null)throw new IllegalArgumentException(Counter+ name +not exist);
return c;
}

public void put(String name){
if(name == null)throw new IllegalArgumentException(null can`t as as name);
if(counters.get(name)!= null)throw new IllegalArgumentException(Counter+ name +exists);
counters.put(name,new Counter(name));
} ...


解决方案

你的问题正在指向你一个很好的方向。由于答案没有提及,所以我将总结一下这个答案的一般想法。



扩展 WebApplicationException / h2>

JAX-RS允许定义Java异常与HTTP错误响应的直接映射。通过扩展 WebApplicationException ,您可以创建应用程序特定的异常,使用状态代码和可选消息构建响应的HTTP响应。



以下异常使用 404构建HTTP响应 状态码:

  public class CustomerNotFoundException extends WebApplicationException {

/ **
*创建HTTP 404(未找到)异常。
* /
public CustomerNotFoundException(){
super(Responsees.notFound()。build());
}

/ **
*创建HTTP 404(未找到)异常。
* @param消息是404响应的实体的String。
* /
public CustomerNotFoundException(String message){
super(Response.status(Responses.NOT_FOUND)。
entity(message).type(text / plain)。建立());
}
}

WebApplicationException 是一个 RuntimeException 并且不需要包裹在中尝试 - catch 阻止或在$ $ c $中声明c> throws 子句:

  @Path(customers / {customerId})
public Customer findCustomer(@PathParam(customerId)Long customerId){
Customer customer = customerService.find(customerId);
if(customer == null){
throw new CustomerNotFoundException(Customer not found with ID+ customerId);
}
返回客户;
}



创建 ExceptionMapper s



在其他情况下,抛出 WebApplicationException ,或扩展 WebApplicationException ,相反,将现有异常映射到响应。



对于这种情况,可以使用自定义异常映射提供程序。提供商必须实施 ExceptionMapper< E扩展Throwable> 界面。例如,以下映射JAP EntityNotFoundException 到HTTP 404 回复:

  @Provider 
public类EntityNotFoundExceptionMapper
实现ExceptionMapper< EntityNotFoundException> {

@Override
public Response toResponse(EntityNotFoundException ex){
return Response.status(404).entity(ex.getMessage())。type(text / plain )。建立();
}
}

当一个 EntityNotFoundException 被抛出, toResponse(将调用 EntityNotFoundExceptionMapper 实例的E) 方法。



@Provider 注释声明该类对JAX-RS运行时感兴趣。此类可以添加到 应用程序 配置的实例。


I have RESTeasy service. And have implemented simple error handling on methods using try catch and feel something is not very 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

response

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;
}
}

exceptions source

public class CounterService {

private Map<String, StatisticCounter> counters = new HashMap<String, StatisticCounter>();

private static CounterService instance = null;

protected CounterService() {}

public static CounterService getInstance() {
      if(instance == null) {
         instance = new CounterService();
      }
      return instance;
}

public StatisticCounter get(String name){
    StatisticCounter c =  counters.get(name);
    if(c == null)throw new IllegalArgumentException("Counter "+name+" not exist");
    return c;
}

public void put(String name){
    if(name==null)throw new IllegalArgumentException("null can`t be as name");
    if(counters.get(name)!=null)throw new IllegalArgumentException("Counter "+name+" exist");
    counters.put(name, new Counter(name));
 }...

解决方案

The comments in your question are pointing you in a good direction. Since the answers do not mention it, I'll summarize the general idea in this answer.

Extending WebApplicationException

JAX-RS allows to define direct mapping of Java exceptions to HTTP error responses. By extending WebApplicationException, you can create application specific exceptions that build a HTTP response with the status code and an optional message as the body of the response.

The following exception builds a HTTP response with the 404 status code:

public class CustomerNotFoundException extends WebApplicationException {

    /**
    * Create a HTTP 404 (Not Found) exception.
    */
    public CustomerNotFoundException() {
      super(Responses.notFound().build());
    }

    /**
    * Create a HTTP 404 (Not Found) exception.
    * @param message the String that is the entity of the 404 response.
    */
    public CustomerNotFoundException(String message) {
      super(Response.status(Responses.NOT_FOUND).
      entity(message).type("text/plain").build());
    }
}

WebApplicationException is a RuntimeException and doesn't need to the wrapped in a try-catch block or be declared in a throws clause:

@Path("customers/{customerId}")
public Customer findCustomer(@PathParam("customerId") Long customerId) {
    Customer customer = customerService.find(customerId);
    if (customer == null) {
        throw new CustomerNotFoundException("Customer not found with ID " + customerId);
    }
    return customer;
}

Creating ExceptionMappers

In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response.

For such cases it is possible to use a custom exception mapping provider. The provider must implement the ExceptionMapper<E extends Throwable> interface. For example, the following maps the JAP EntityNotFoundException to a HTTP 404 response:

@Provider
public class EntityNotFoundExceptionMapper 
    implements ExceptionMapper<EntityNotFoundException> {

    @Override
    public Response toResponse(EntityNotFoundException ex) {
      return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
    }
}

When an EntityNotFoundException is thrown, the toResponse(E) method of the EntityNotFoundExceptionMapper instance will be invoked.

The @Provider annotation declares that the class is of interest to the JAX-RS runtime. Such class may be added to the set of classes of the Application instance that is configured.

这篇关于如何在类方法中删除try / catch重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆