youssef
youssef

Reputation: 159

How to return error message and HTTP status code together?

I'm using JAX-RS and I want to display the HTTP status and an error message.

Example: HTTP 204 No Content

Here is my code:

public Response getMessageById(@Context HttpServletRequest request, 
 @PathParam("idMessage") BigInteger idMessage){
 if (idMessage== null){
        return Response.status(HttpURLConnection.HTTP_NO_CONTENT)
               .entity("No Content").build(); 
    }
 }

It displays No Content without the HTTP status.

Upvotes: 0

Views: 673

Answers (1)

R2C2
R2C2

Reputation: 728

HTTP defines a response header and a response body. The latter one is set by calling entity(), the former by status(). So what you actually send is this:

204 No Content

No Content

You just don't see the header if the tool you use does not display it by default. Use for example curl -v http://your-rest-service/api/resource so see it.

Furthermore:

  • Don't return 204 if an id is missing. This would rather be a 400 or 404 depending on the sematics. 204 is for operations that don't need to return anything (like PUT, POST, DELETE).
  • I doubt that this parameter can be null. JaxRS will not select the method if the request does not match the @Path.
  • Although using the constants in HttpURLConnection is possible, it would be more consistent to use javax.ws.rs.core.Response.Status
  • HttpServletRequest is for rare edge cases only. Don't use it if you don't need it.

Upvotes: 1

Related Questions