lap*_*ots 9 java annotations exception
有没有办法创建自己的注释来处理异常?
我的意思是,例如,如果方法抛出一些异常,而不是创建try-catch块我想在方法上添加注释 - 并且它不需要使用try-catch.
例如像这样的东西
public void method() {
try {
perform();
} catch (WorkingException e) {
}
}
@ExceptionCatcher(WorkingException.class)
public void method() {
perform();
}
Run Code Online (Sandbox Code Playgroud)
小智 0
AspectJ 非常适合这个用例。这段代码将把任何用@ExceptionCatcher注释的方法包装在try-catch中,检查抛出的异常是否是应该处理的类型(基于@ExceptionCatcher中定义的类),然后运行自定义逻辑或重新抛出。
注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface ExceptionCatcher {
public Class<? extends Throwable>[] exceptions() default {Exception.class};
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2607 次 |
| 最近记录: |