Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何删除类方法中的try/catch重复?_Java_Rest_Design Patterns - Fatal编程技术网

Java 如何删除类方法中的try/catch重复?

Java 如何删除类方法中的try/catch重复?,java,rest,design-patterns,Java,Rest,Design Patterns,我有简单的服务。并且在使用try-catch的方法上实现了简单的错误处理,但感觉有些不太好。我注意到我所有的方法都在重复。所以我想问一下如何避免重复(减少代码大小)try catch,但不丢失功能 @Path("/rest") @Logged @Produces("application/json") public class CounterRestService { @POST @Path("/create") public CounterResponce create(@Que

我有简单的服务。并且在使用
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().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
回应

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;
}
}
异常源

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));
 }...
公共类反服务{
私有映射计数器=新的HashMap();
私有静态CounterService实例=null;
受保护的反服务(){}
公共静态计数器服务getInstance(){
if(实例==null){
实例=新的CounterService();
}
返回实例;
}
公共StatisticCounter获取(字符串名称){
StatisticCounter c=counters.get(名称);
如果(c==null)抛出新的IllegalArgumentException(“计数器”+name+“不存在”);
返回c;
}
公共void put(字符串名称){
如果(name==null)抛出新的IllegalArgumentException(“null不能作为name”);
如果(counters.get(name)!=null)抛出新的IllegalArgumentException(“Counter”+name+“exist”);
计数器。放置(名称,新计数器(名称));
}...
  • 引入一个私有方法,如“apply”,如果使用Java 8,它可以将函数作为参数。该方法将集中处理错误和/或映射、响应映射和响应生成代码
  • 在create和delete方法中,调用此apply方法并传递希望作为lambda表达式执行的所需计数器操作

  • 你问题中的评论为你指明了一个好的方向。因为答案中没有提到这一点,所以我将在这个答案中总结总体思路

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

    以下异常生成状态代码为的HTTP响应:

    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());
        }
    }
    
    是,不需要包装在
    try
    -
    catch
    块中,也不需要在
    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);
        }
        return customer;
    }
    
    创建
    ExceptionMapper
    s 在其他情况下,可能不适合抛出扩展的实例或类,相反,最好将现有异常映射到响应

    对于这种情况,可以使用自定义异常映射提供程序。该提供程序必须实现该接口。例如,以下内容将JAP映射到HTTP响应:

    @Provider
    public class EntityNotFoundExceptionMapper 
        implements ExceptionMapper<EntityNotFoundException> {
    
        @Override
        public Response toResponse(EntityNotFoundException ex) {
          return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
        }
    }
    
    @Provider
    公共类EntityNotFoundExceptionMapper
    实现ExceptionMapper{
    @凌驾
    公众响应(EntityNotFoundException ex){
    返回Response.status(404).entity(例如getMessage()).type(“text/plain”).build();
    }
    }
    
    抛出时,将调用
    EntityNotFoundExceptionMapper
    实例的方法


    注释声明JAX-RS运行时对该类感兴趣。可以将此类添加到已配置实例的类集合中。

    我认为您不需要try-catch,因为您要添加到post的代码中不太可能存在异常谢谢,这正是我在寻找的C#中的相关问题:谢谢听起来不错,但我使用Java 7,所以我不能使用函数作为参数。另一方面,现在是开始使用它的好时机:)