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:

  1. In your aspect class, create an advice method annotated with @AfterThrowing. Make it take a JoinPoint object and an Exception object as arguments:
    @AfterThrowing(pointcut="execution(* com.spring_cookbook.controllers.*.*(..))", throwing="exception")
    public void logException(JoinPoint joinPoint, Exception exception) {
    ...
    }
  2. In that advice method, log ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.