我使用@ControllerAdvice, @ErrorHandler和@ResponseStatus注释来返回一些错误信息。我确信处理程序方法被执行了(我已经在调试器下检查了它)。但是我的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());
}
这里是类似的问题,但它不包含一个正确的答案,因为我试图避免使我的代码复杂化。禁用Tomcat中所有默认的HTTP错误响应内容
试试这个:
@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);
}