2015-12-30 84 views
1

我在dropwizard中构建了一个通用的异常处理程序。我想提供自定义的注释作为库的一部分,它将调用时例外方法提出了handleException方法(方法包含注释)使用自定义注释的调用方法 - JAVA

详情: 自定义注释@ExceptionHandler

@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface ExceptionHandler{ 
    Class<? extends Throwable>[] exception() default {}; 
} 

有一个处理方法handleException(Exception, Request),类ExceptionHandlerImpl

现在有每当EXC1EXC2由法doPerformOperation提出有法注释

@ExceptionHandler(exception = {EXC1,EXC2}) 
Response doPerformOperation(Request) throws EXC1,EXC2,EXC3{} 

现在商务舱,我想调用handleException方法。

我尝试阅读AOP(AspectJ),Reflection,但无法找出执行此操作的最佳最佳方式。

+0

无论如何,这个异常是否应该被记录并升级到调用堆栈,或者您是否期望异常被捕获并且问题“修复”?我在问,因为如果你想修复它,你需要生成一个'Response'来由你的方法返回。我建议的解决方案取决于你的答案。 – kriegaex

+1

标准JAX-RS异常映射器(https://jersey.java.net/documentation/latest/representations.html#d0e6653)会更明智吗?并根据异常类型提供异常处理程序? –

+0

@ kriegaex:我不需要任何返回值。我已经使用aspectjrt解决了这个问题。 –

回答

1

我已经使用aspectj解决了这个问题。我创建了接口

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface HandleExceptionSet { 
    HandleException[] exceptionSet(); 
} 

其中HandleException是另一个注释。这是为了允许一些例外。

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.ANNOTATION_TYPE) 
public @interface HandleException { 
    Class<? extends CustomException> exception() default CustomException.class; 
} 

现在我有一个ExceptionHandler类,它有处理程序。为了将方法绑定到这个注解,我在模块中使用下面的配置。

bindInterceptor(Matchers.any(), Matchers.annotatedWith(HandleExceptionSet.class), new ExceptionHandler()); 

我在类中使用这个注释,下面的代码片段。

@HandleExceptionSet(exceptionSet = { 
     @HandleException(exception = ArithmeticException.class), 
     @HandleException(exception = NullPointerException.class), 
     @HandleException(exception = EntityNotFoundException.class) 
}) 
public void method()throws Throwable { 
    throw new EntityNotFoundException("EVENT1", "ERR1", "Entity Not Found", "Right", "Wrong"); 
} 

这现在正在为我工​​作。不确定,如果这是最好的方法。

有没有更好的方法来实现这个目标?