Search code examples
javarestspring-mvctomcattomcat8

How to disable Tomcat's html error pages when my REST API returns 500 HTTP Status


I'm using @ControllerAdvice, @ErrorHandler and @ResponseStatus annotations to return some error informations. I'm sure that handler method is executed (I've checked it under debuger.) But my ErrorInfo object is overriden by Tomcat HTML error page.

@ExceptionHandler(value = ServiceExecutionException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal Server Error")
ErrorInfo handleServiceError(HttpServletRequest request, HttpServletResponse response, Exception e) {
    return new ErrorInfo(request.getRequestURL().toString(), e.getLocalizedMessage());
}

Here is similar question, but it doesn't contains a proper answer, because I try to avoid complicating my code. Disable all default HTTP error response content in Tomcat


Solution

  • Try this:

    @ExceptionHandler(ServiceExecutionException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity<ErrorInfo> handleServiceError(ServiceExecutionException ex,
                HandlerMethod handlerMethod, WebRequest webRequest) {
       String url = ((ServletWebRequest)webRequest).getRequest().getRequestURL().toString();
       ErrorInfo errorInfo = new ErrorInfo(url, ex.getLocalizedMessage());
       return new ResponseEntity<ErrorInfo>(errorInfo, HttpStatus.INTERNAL_SERVER_ERROR);
    }