Logging exceptions using an after-throwing advice
An after-throwing advice executes some extra code when an exception is thrown during the execution of the target method. In this recipe, we will just log the exception.
Getting ready
We will use the aspect class defined in the Creating a Spring AOP aspect class recipe.
How to do it…
Here are the steps for logging an exception using an after-throwing advice:
- In your aspect class, create an advice method annotated with
@AfterThrowing
. Make it take aJoinPoint
object and anException
object as arguments:@AfterThrowing(pointcut="execution(* com.spring_cookbook.controllers.*.*(..))", throwing="exception") public void logException(JoinPoint joinPoint, Exception exception) { ... }
- In that advice method, log the exception preceded by the target method name:
String className = joinPoint.getSignature().getDeclaringTypeName(); String methodName = joinPoint.getSignature().getName(); System.out.println("-----" + className...