【问题标题】:How to swallow a exception at AfterThrowing in AspectJ如何在 AspectJ 的 AfterThrowing 中吞下异常
【发布时间】:2023-03-21 11:45:01
【问题描述】:

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

上面,它没有吞下异常。 testThrowable() 的调用者仍然收到异常。我希望来电者不要收到异常。怎么能做到这一点? 谢谢。

【问题讨论】:

    标签: java aspectj


    【解决方案1】:

    我认为这在AfterThrowing 中是做不到的。您需要使用Around

    【讨论】:

      【解决方案2】:

      我的解决方案!

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

      再次感谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-26
        • 1970-01-01
        • 2019-03-08
        • 1970-01-01
        • 1970-01-01
        • 2013-06-22
        • 2010-11-01
        • 2018-08-25
        相关资源
        最近更新 更多