Search code examples
javaspringrestaopspring-aop

How to log rest controller exceptions by using Spring AOP?


I have a rest controller and Spring AOP class which catches service level custom exceptions and logs them but I also need to log the exceptions from controller side.

Here's my Spring AOP class;

@Aspect
@Component
public class ExceptionLoggerAspect {

    @AfterThrowing(pointcut = "execution(* com.b.m.service.GaService.*(..)) ", throwing = "ex")
    public void logError(JoinPoint joinPoint, GaException ex) {
        Signature signature = joinPoint.getSignature();
        String methodName = signature.getName();
        String stuff = signature.toString();
        String arguments = Arrays.toString(joinPoint.getArgs());
        LOGGER.error("Exception have been caught in method:\n "
                + "[" + methodName + "] with arguments "
                + arguments + " and the full toString: [" + stuff + "] \n the exception is: ["
                + ex.type.getMessage() + " - " + ex.type.getAdditionalInfo() + "]");
    }
} 

How can I add my controller class here to log the exceptions? I added my controller package path with "execution" pointcut but it doesn't work.


Solution

  • Starting from Spring 3.2, you could use @ControllerAdvice which allows us to consolidate our multiple, scattered @ExceptionHandlers from before into a single, global error handling component. This would also allow us to have full control over the body of the response as well as the status code.

    @ControllerAdvice
    public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHandler {
        @ExceptionHandler(value = {Exception.class})
        public ResponseEntity<Object> handleGenericExceptions(Exception exception, WebRequest webRequest) {
            log.error("Handling: ", exception);
    
            HttpStatus errorCode = HttpStatus.INTERNAL_SERVER_ERROR;
    
            return this.handleExceptionInternal(exception, "Unexpected Internal Server Error", new HttpHeaders(), errorCode, webRequest);
        }
    }