【问题标题】:Create custom annotation to handle exceptions创建自定义注解来处理异常
【发布时间】:2015-06-24 01:42:37
【问题描述】:

有没有办法创建自己的注释来处理异常?

我的意思是,例如,如果方法抛出一些异常,而不是创建 try-catch 块,我想在方法上添加注释 - 并且不需要使用 try-catch

比如这样的

public void method() {
    try {
        perform();
    } catch (WorkingException e) {
    }
}

@ExceptionCatcher(WorkingException.class)
public void method() {
    perform();
}

【问题讨论】:

  • 这可能会有所帮助.... 之前在 SO [using-annotations-for-exception-handling][1] [1] 上询问过它:stackoverflow.com/questions/19389808/…
  • @NeerajJain 如果 OP 想要注释怎么办?
  • @NeerajJain throws 将异常传递给调用方法,OP想要实现的是通过注解处理异常,应该可以,Mohit Gupta已经提供了很好的链接

标签: java exception annotations


【解决方案1】:

AspectJ 非常适合这个用例。这段代码会将任何带有@ExceptionCatcher 注解的方法包装在一个try-catch 中,检查抛出的异常是否是应该处理的类型(基于@ExceptionCatcher 中定义的类),然后运行自定义逻辑或重新抛出。

注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface ExceptionCatcher {
    public Class<? extends Throwable>[] exceptions() default {Exception.class};
}

AspectJ 建议:

@Aspect
public class ExceptionCatchingAdvice {
    @Around("execution(@ExceptionCatcher * *.*(..)) && @annotation(ExceptionCatcher)")
    public Object handle(ProceedingJoinPoint pjp, ExceptionCatcher catcher) throws Throwable {
        try {
            // execute advised code
            return pjp.proceed();
        }
        catch (Throwable e) {
            // check exceptions specified in annotation contain thrown exception
            if (Arrays.stream(catcher.exceptions())
                      .anyMatch(klass -> e.getClass().equals(klass))) {
                // custom logic goes here
            }
            // exception wasn't specified, rethrow
            else {
                throw e;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 2017-11-09
    • 2011-06-11
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多