如何在方面委托异常

时间:2017-11-07 13:50:27

标签: java exception-handling aspect

我有外部jar库,我创建了方面来处理某些情况:

@Aspect
@Component
public class MyAspect {

    @Around("execution(..")
    private Object process(ProceedingJoinPoint pjp) throws Throwable {
        Exception ex = null;

        while (zkusDalsiSpojeni) {
            try {
                return pjp.proceed();
            } catch (Exception e) {
               solveException(ex);
            }
        }
    }
}

是的,我可以在这里抛出一些例外。但是我也希望选择在主项目中抛出一个自定义异常,将这个jar作为依赖。如何做到最好的方法是什么? (抽象方面或一些委托人?)

1 个答案:

答案 0 :(得分:0)

如果您将方面与接口一起使用,则可以定义注释

@Target(ElementType.Method)
@Retention(RetentionPolicy.Runtime)
@interface DesiredException {
   Class<? extends Throwable> value();
}

并适用于所需方法

@DesiredException(IllegalStateException.klass)

在您的方面,您可以检查是否声明了此注释,并采取相应的行动

MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
DesiredException desiredException = methodSignature.getMethod().getAnnotation(DesiredException.class);
if(desiredException!=null){
    Throwable exception = desiredException.value().newInstance();
    throw exception; 
}