Home > database >  How to log rest controller exceptions by using Spring AOP?
How to log rest controller exceptions by using Spring AOP?

Time:12-08

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.

CodePudding user response:

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);
    }
}

CodePudding user response:

Use @ControllerAdivce

@Slf4j
@ControllerAdvice
@RestController
public class GlobalExceptionHandler {
 @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex) {
        log.error("Exception occurred", ex);
        ErrorResponse errorResponse = ErrorResponse.builder().code(Error.UNKNOWN_ERROR.getCode())
                .message(Error.UNKNOWN_ERROR.getMessage()).build();
        return new ResponseEntity<>(errorResponse, Error.UNKNOWN_ERROR.getHttpStatus());
    }
}

Use a Error Response Bean to send the rest response.

public class ErrorResponse implements Serializable {
    private static final long serialVersionUID = -2405172041950251807L;
    private Integer code;
    private String message;
}
  • Related