How to keep ResponseBody on 204 No Content response?

Viewed 22320

I want to return a 204 no content http status code. Though I want to add a custom error messages that gives details why where was no content.

Problem: I'm using spring-mvc, and when returning HttpStatus.NO_CONTENT type, the response body is always removed and empty for the client!

@RestControllerAdvice
public class ExeptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Object handler(HttpServletRequest req, Exception e) {
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.NO_CONTENT);
    }
}

If I change the type eg to HttpStatus.NOT_FOUND then the error message is shown as response body.

How can I achieve the same with 204?

2 Answers

I want to return a 204 no content HTTP status code. Though I want to add a custom error messages that gives details why where was no content.

You can't.

Problem: I'm using Spring MVC, and when returning HttpStatus.NO_CONTENT type, the response body is always removed and empty for the client!

That's the expected behaviour.

If I change the type eg to HttpStatus.NOT_FOUND then the error message is shown as response body. How can I achieve the same with 204?

You won't achieve it with 204. You are misunderstanding (and probably misusing) such status code. The purpose of 204 is to indicate that the server has successfully fulfilled the request and there's not additional content to send in the response payload.

For reference, see how this status code is defined in the RFC 7231:

6.3.5. 204 No Content

The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body. [...]

A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body. [...]


Depending on the situation, you'd better use 404 or 200 with an empty array in the response payload. This answer may give you some insights.

204 is for successful requests. It should have no error message included.

If an error happened, a different HTTP Code should be used.

see https://httpstatuses.com/204

A 204 response is terminated by the first empty line after the header fields because it cannot contain a message body.

Related