How to swallow a exception at AfterThrowing in AspectJ

纵然是瞬间 提交于 2019-12-21 09:35:00

问题


In AspectJ, I want to swallow a exception.

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

Above, it didn't swallow exception. The testThrowable()'s caller still received the exception. I want caller not to receive exception. How can do this? Thanks.


回答1:


I think it can't be done in AfterThrowing. You need to use Around.




回答2:


My solution!

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

}

Thanks again.



来源:https://stackoverflow.com/questions/4396167/how-to-swallow-a-exception-at-afterthrowing-in-aspectj

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!