How to disable Tomcat html error pages when my REST API returns 500 HTTP status

I use the annotations @ControllerAdvice, @ErrorHandler and @ResponseStatus to return some error information. I am sure that the handler method has completed (I checked it in the debugger). But my ErrorInfo object is overridden by the 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 a similar question, but it does not contain the correct answer, because I try not to complicate my code. Disable all contents of default HTTP error response in Tomcat

+7
source share
1 answer

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

Source: https://habr.com/ru/post/1610626/


All Articles