我正在dropwizard中构建一个通用异常处理程序。我想提供自定义注释作为库的一部分,当方法(包含注释的方法)中出现异常时,它将调用handleException方法
详细信息:自定义注释为@ExceptionHandler
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExceptionHandler{
Class<? extends Throwable>[] exception() default {};
}
类ExceptionHandlerImpl
中有一个处理程序方法handleException(Exception, Request)
。
现在有一个业务类具有带注释的方法
@ExceptionHandler(exception = {EXC1,EXC2})
Response doPerformOperation(Request) throws EXC1,EXC2,EXC3{}
现在,每当方法doPerformOperation
引发EXC1
和EXC2
时,我都想调用handleException
方法。
我试着阅读关于AOP(AspectJ)、Reflection的文章,但没能找出执行这一操作的最佳方式。
我已经使用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类,它有一个handler。为了将一个方法绑定到这个注释,我在模块中使用以下配置。
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");
}
这对我来说很有效。不确定,这是否是最好的方法。
有没有更好的方法来实现这一点?