如何在方面委派异常



>我有外部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将作为依赖项。最好的方法是什么?(抽象方面还是一些委托人?

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

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

最新更新