![](/img/trans.png)
[英]Spring Boot @ControllerAdvice exception handler not firing
[英]Spring Boot @ControllerAdvice Exception Handler not returning HTTP Status Text
我有一个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修复此问题
@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
您可以访问一堆预先配置的异常处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.