When creating a controller in Spring Boot to handle all errors/exceptions in a custom way, including custom exceptions,
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);
}
}