[英]Spring Boot @ControllerAdvice Exception Handler not returning HTTP Status Text
I have a GlobalExceptionHandler
that catches exceptions and returns a HTTP Error codes. 我有一个
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());
}
...
}
This works correctly and responds with a 404
. 这可以正常工作,并以
404
响应。 But the HTTP response looks like this: 但HTTP响应如下所示:
HTTP/1.1 404
X-Application-Context: application:8080
Content-Length: 0
Date: Wed, 03 Aug 2016 14:36:52 GMT
But should return: 但是应该回归:
HTTP/1.1 404 Not Found
X-Application-Context: application:8080
Content-Length: 0
Date: Wed, 03 Aug 2016 14:36:52 GMT
The Not Found
part is missing. 缺少
Not Found
部分。 This is the same for other errors. 其他错误也是如此。 eg
500 - Internal Server Error
例如
500 - Internal Server Error
Any ideas in how to include this? 关于如何包含这个的任何想法?
Update: Downgrading from Spring Boot 1.4.0 to 1.3.7 fixed this 更新:从Spring Boot 1.4.0降级到1.3.7修复此问题
From the release notes : 从发行说明 :
Server header
服务器头
The Server HTTP response header is no longer set unless the
server.server-header
property is set.除非设置了
server.server-header
属性,否则不再设置Server HTTP响应头。
This seems like it might be the cause of your issue. 这似乎可能是您的问题的原因。
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
by extending this class you can override default spring behavior. 通过扩展此类,您可以覆盖默认的弹簧行为。
@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)
is ok, but to get more control over response use ResponseEntity
. @ResponseStatus(HttpStatus.NOT_FOUND)
,但为了更好地控制响应,请使用ResponseEntity
。 Also by extending ResponseEntityExceptionHandler
you get access to bunch of preconfigured exception handlers. 此外,通过扩展
ResponseEntityExceptionHandler
您可以访问一堆预先配置的异常处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.