Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 the exception preceded by the target method name:

    String className = joinPoint.getSignature().getDeclaringTypeName();
    String methodName = joinPoint.getSignature().getName();
    System.out.println("-----" + className + "." + methodName + "() -----");
    System...