简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM