我有GlobalExceptionHandler
捕获异常并返回HTTP错误代码。
@ControllerAdvice
@Component
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
...
// 404 - Not Found
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void requestHandlingNoHandlerFound(HttpServletRequest request, Exception exception) {
logger.error("Error Not Found (404): " + exception.getMessage());
}
...
}
这可以正常工作,并以404
回复。但HTTP响应如下所示:
HTTP/1.1 404
X-Application-Context: application:8080
Content-Length: 0
Date: Wed, 03 Aug 2016 14:36:52 GMT
但应该回复:
HTTP/1.1 404 Not Found
X-Application-Context: application:8080
Content-Length: 0
Date: Wed, 03 Aug 2016 14:36:52 GMT
缺少Not Found
部分。其他错误也是如此。例如500 - Internal Server Error
有关如何包含此内容的任何想法?
更新 从Spring Boot 1.4.0降级到1.3.7修复了这个
答案 0 :(得分:3)
答案 1 :(得分:1)
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
通过扩展此类,您可以覆盖默认的弹簧行为。
@ExceptionHandler({NoHandlerFoundException.class,EntityNotFoundException.class})
protected ResponseEntity<Object> handleNotFound(final RuntimeException ex,final WebRequest request) {
final MyError myError= new MyError (HttpStatus.NOT_FOUND, ex);
return handleExceptionInternal(ex, myError, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
@ResponseStatus(HttpStatus.NOT_FOUND)
没问题,但为了更好地控制使用ResponseEntity
的响应。此外,通过扩展ResponseEntityExceptionHandler
,您可以访问一堆预先配置的异常处理程序。