【问题标题】:Invoke Method Using Custom Annotation - JAVA使用自定义注释调用方法 - JAVA
【发布时间】:2016-02-26 19:14:31
【问题描述】:

我正在 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{}

现在每当EXC1 和EXC2 由方法doPerformOperation 引发时,我想调用handleException 方法。

我尝试阅读有关 AOP(AspectJ)、反射的内容,但无法找出执行此操作的最佳方式。

【问题讨论】:

  • 是否应该只记录异常并将异常升级到调用堆栈,还是您希望捕获异常并“修复”问题?我问是因为如果你想修复它,你需要生成一个 Response 以由你的方法返回。我可能建议的解决方案取决于您的回答。
  • 对标准 JAX-RS 异常映射器 (jersey.java.net/documentation/latest/…) 是否更明智并根据异常类型提供异常处理程序?
  • @kriegaex :我不需要任何返回值。我已经使用 aspectjrt 解决了这个问题。

标签: java annotations aop aspectj dropwizard


【解决方案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());

我在类中使用这个注解,下面是sn-p。

@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");
}

这现在对我有用。 不确定,如果这是最好的方法。

有没有更好的方法来实现这一点?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2019-12-24
    相关资源
    最近更新 更多