![](/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.