我正在 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 类,它有处理程序。要将方法绑定(bind)到此注释,我在模块中使用以下配置。
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");
}
这现在对我有用。 不确定这是否是最好的方法。
有没有更好的方法来实现这个目标?
关于java - 使用自定义注释调用方法 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34523429/