Spring Boot @ControllerAdvice异常处理程序不返回HTTP状态文本

时间:2016-08-03 14:39:10

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

我有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修复了这个

2 个答案:

答案 0 :(得分:3)

来自release notes

  

服务器标头

     

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

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

答案 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,您可以访问一堆预先配置的异常处理程序。