Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swallow a exception at AfterThrowing in AspectJ

Tags:

java

aspectj

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.

like image 278
user389227 Avatar asked Dec 09 '10 08:12

user389227


2 Answers

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

like image 80
Tadeusz Kopec for Ukraine Avatar answered Oct 06 '22 18:10

Tadeusz Kopec for Ukraine


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.

like image 27
user389227 Avatar answered Oct 06 '22 17:10

user389227