【问题标题】:Spring Boot @ControllerAdvice Exception Handler not returning HTTP Status TextSpring Boot @ControllerAdvice 异常处理程序不返回 HTTP 状态文本
【发布时间】:2016-12-09 08:37:45
【问题描述】:

我有一个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 解决了这个问题

【问题讨论】:

  • 我真的,真的希望你的意思是 Spring Boot 1.4.0 -> 1.3.7

标签: java spring rest spring-mvc spring-boot


【解决方案1】:

来自release notes

服务器头

除非设置了 server.server-header 属性,否则不再设置服务器 HTTP 响应标头。

这似乎是您的问题的原因。

【讨论】:

  • 谢谢,这需要设置成什么?
  • 哈,我的错 - 适用于完全不同的东西。这看起来像是一种回归,可能值得为此报告一个错误。
  • 来自tomcat.apache.org/tomcat-8.5-doc/changelog.html:RFC 7230 规定客户端应忽略 HTTP/1.1 响应消息中的原因短语。由于原因短语是可选的,Tomcat 不再发送它。
【解决方案2】:
@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,您可以访问一堆预配置的异常处理程序。

【讨论】:

  • 我会试一试的。谢谢:)
猜你喜欢
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 2018-01-15
  • 2018-12-30
  • 2019-02-25
  • 2018-07-13
相关资源
最近更新 更多