Using Spring Boot's ErrorController and Spring's ResponseEntityExceptionHandler correctly

后端 未结 2 1738
独厮守ぢ
独厮守ぢ 2021-02-02 00:33

The Question

When creating a controller in Spring Boot to handle all errors/exceptions in a custom way, including custom exceptions,

2条回答
  •  野性不改
    2021-02-02 00:51

    I will admit that I am not overly familiar with Spring's ErrorController, but looking at your specified goals I believe all of them can be achieved cleanly using Spring's @ControllerAdvice. The following is an example how I have been using it in my own applications:

    @ControllerAdvice
    public class ExceptionControllerAdvice {
    
        private static final String INCOMING_REQUEST_FAILED = "Incoming request failed:";
        private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionControllerAdvice.class);
        private final MessageSource source;
    
        public ExceptionControllerAdvice2(final MessageSource messageSource) {
            source = messageSource;
        }
    
        @ExceptionHandler(value = {CustomException.class})
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public ErrorMessage badRequest(final CustomException ex) {
            LOGGER.error(INCOMING_REQUEST_FAILED, ex);
            final String message = source.getMessage("exception.BAD_REQUEST", null, LocaleContextHolder.getLocale());
            return new ErrorMessage(HttpStatus.BAD_REQUEST.value(), message);
        }
    
        @ExceptionHandler(Throwable.class)
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        @ResponseBody
        public ErrorMessage internalServerError(final Exception ex) {
            LOGGER.error(INCOMING_REQUEST_FAILED, ex);
            final String message =
                    source.getMessage("exception.INTERNAL_SERVER_ERROR", null, LocaleContextHolder.getLocale());
            return new ErrorMessage(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
        }
    }
    

提交回复
热议问题