views:

751

answers:

1

Hey there,

when trying to implement an Aspect, that is responsible for catching and logging a certain type of error, I initially thought this would be possible using the AfterThrowing advice. However it seems that his advice doesn't catch the exception, but just provides an additional entry point to do something with the exception.

The only advice which would also catch the exception in question would then be an AroundAdvice - either that or I did something wrong.

Can anyone assert that indeed if I want to catch the exception I have to use an AroundAdvice? The configuration I used follows:

@Pointcut("execution(* test.simple.OtherService.print*(..))")
public void printOperation() {}

@AfterThrowing(pointcut="printOperation()", throwing="exception")
public void logException(Throwable exception) {
  System.out.println(exception.getMessage());
}

@Around("printOperation()")
public void swallowException(ProceedingJoinPoint pjp) throws Throwable {
  try {
    pjp.proceed();
  } catch (Throwable exception) {
    System.out.println(exception.getMessage());
  }
}

Note that in this example I caught all Exceptions, because it just is an example. I know its bad practice to just swallow all exceptions, but for my current use case I want one special type of exception to be just logged while avoiding duplicate logging logic.

+1  A: 

The Spring reference doc says:

"After throwing advice runs when a matched method execution exits by throwing an exception"

By then it's too late to catch the exception as it has already been thrown and the method has exited. The approach you've taken with the @Around advice is the only way to actually catch the exception and deal with it before the method exits.

Shane Bell
I don't actually think this is true. I believe that the handler join point is the way to catch the exception and deal with it before the method exits. Around advice will allow you to catch the exception after the method has thrown the exception and returned.Please see http://www.eclipse.org/aspectj/doc/next/progguide/language-joinPoints.html
Tim Hennekey