如何在AspectJ中的AfterThrowing中吞下异常

use*_*227 8 java aspectj

在AspectJ中,我想吞下一个异常.

@Aspect
public class TestAspect {

 @Pointcut("execution(public * *Throwable(..))")
 void throwableMethod() {}

 @AfterThrowing(pointcut = "throwableMethod()", throwing = "e")
 public void swallowThrowable(Throwable e) throws Exception {
  logger.debug(e.toString());
 }
}

public class TestClass {

 public void testThrowable() {
  throw new Exception();
 }
}
Run Code Online (Sandbox Code Playgroud)

上面,它没有吞下异常.testThrowable()的调用者仍然收到异常.我希望来电者不要收到例外.怎么办呢?谢谢.

Tad*_*pec 6

我认为不能这样做AfterThrowing.你需要使用Around.


use*_*227 5

我的解决方案

@Aspect
public class TestAspect {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(public * *Throwable(..))")
    void throwableMethod() {}

    @Around("throwableMethod()")
    public void swallowThrowing(ProceedingJoinPoint pjp) {
        try {
            pjp.proceed();
        } catch (Throwable e) {
            logger.debug("swallow " + e.toString());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

再次感谢.