Search code examples
springspring-mvcspring-aop

Spring AOP Advice for ResponseEntityExceptionHandler.handleException


I am new at Spring AOP. I try to write advice for ResponseEntityExceptionHandler.handleException method to logging exception info. After hours of searching for solutions, I'm stuck.

This is my Apect component

@Log4j2
@Aspect
@Component
public class LogginAspect {

  @Pointcut(value = "execution(* org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(..)) && args(ex, request)")
  public void callSpringExceptionHandler() {}

  @Before("callSpringExceptionHandler()")
  public void logBeforeError(JoinPoint joinPoint, Exception ex, WebRequest request) {
    log.error(ex.getMessage(), ex);
  }
}

I have tried different patterns of pointcut but with no luck. My advice logBeforeError does not ever called at all. Please help me with my problem


Solution

  • From the Spring documentation :5.8. Proxying Mechanisms

    If the target object to be proxied implements at least one interface, a JDK dynamic proxy is used. All of the interfaces implemented by the target type are proxied. If the target object does not implement any interfaces, a CGLIB proxy is created.

    and

    With CGLIB, final methods cannot be advised, as they cannot be overridden in runtime-generated subclasses.

    ResponseEntityExceptionHandler is an abstract class which does not implement any interface and ResponseEntityExceptionHandler.handleException() is a final method. In short Spring AOP will not be able to advice that method execution.

    You will be able to achieve advicing a final method using AspectJ though. Please go through the detailed answer from @kriegaex