3

(this is an edit of the original question to make clear that this question is not a duplicate - the question marked as duplicate deals with returning custom error messages in the response, not custom reason phrases to official error codes).

I am trying to return a 'custom reason phrase' for a given Http error code in a restful service (not create a custom code or return custom content in the response), and WebApplicationException(msg, code) is failing at that. I have just found a related post explaining how to create custom Status objects for http responses (JAX/Jersey Custom error code in Response) and will look into it to see if this can be used as a work-around. However, would still like to know if the Jersey folks are working on resolving this issue. I am using version 2.13 of Jersey.

More info on this problem: the HttpServletResponse.sendError(int code, String msg) method does in fact work as expected (when called directly), but it appears to be the case that the 'msg' parameter in the WebApplicationException(msg, code) call gets lost before the HttpServletResponse.sendError method gets called. As a consequence, clients of the service always see the default Http error code reason phrase in the response.

Community
  • 1
  • 1
pgoldweic
  • 467
  • 3
  • 9

1 Answers1

0

As you noted, the default behavior is that the exception's detail message is not included in the HTTP response.

You can define a custom ExceptionMapper that will do what you want. Here is a simple example:

@Provider
public class CustomExceptionMapper implements ExceptionMapper<ClientErrorException> {
    @Override
    public Response toResponse(ClientErrorException ex) {
        return Response.status(ex.getResponse().getStatus())
                .entity(ex.getResponse().getStatus() + " " + ex.getMessage())
                .type(MediaType.TEXT_PLAIN).
                build();
    }
}

This example customizes Jersey's response for any exception that is a subclass of ClientErrorException (e.g. BadRequestException, ForbiddenException, etc.) Note that it is including the exception's message (ex.getMessage) in the body of the response. Although this response is plain text it could just as easily return JSON.

There are lots of (better?) examples out there once you know what to look for.

Bampfer
  • 2,120
  • 16
  • 25