简体   繁体   中英

Spring Boot @ControllerAdvice Exception Handler not returning HTTP Status Text

I have a GlobalExceptionHandler that catches exceptions and returns a HTTP Error codes.

@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 . But the HTTP response looks like this:

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. This is the same for other errors. eg 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

From the release notes :

Server header

The Server HTTP response header is no longer set unless the server.server-header property is set.

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 . Also by extending ResponseEntityExceptionHandler you get access to bunch of preconfigured exception handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM