当我的 REST API returns 500 HTTP 状态时如何禁用 Tomcat 的 html 错误页面

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

我正在使用@ControllerAdvice、@ErrorHandler 和@ResponseStatus 注释 return 一些错误信息。我确信处理程序方法已执行(我已经在调试器下检查过它。)但是我的 ErrorInfo 对象被 Tomcat HTML 错误页面覆盖。

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

这是一个类似的问题,但它没有包含正确的答案,因为我尽量避免使我的代码复杂化。

试试这个:

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