Re: [Jersey] Customize default error responses

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 02 Feb 2010 15:21:02 +0100

On Feb 2, 2010, at 3:08 PM, Robert Koberg wrote:

> On Feb 2, 2010, at 2:15 AM, Paul Sandoz wrote:
>> Hi Chris,
>> Jersey will always throw a WebApplicationException for HTTP error-
>> based responses, and only the status code (and potentially some
>> headers) will be set, the entity will not be set.
>> So you can register an ExceptionMapper for WebApplicationException.
>> JAX-RS/Jersey will re-throw any exception that is not mapped to the
>> container.
>> Thus for full mapping i recommend doing the following:
>> - register an ExceptionMapper<WebApplicationException> to modify
>> responses, perhaps specific to the HTTP status code.
>> - register an ExceptionMapper<Throwable> to catch all other
>> exceptions, perhaps with a generic response signaling a 500
>> sever error.
> In Tomcat, the only way I could see how to ensure all errors come
> back as JSON, was to create a Tomcat specific Valve that extends
> org.apache.catalina.valves.ErrorReportValve. For Tomcat at least,
> the default error valve is hard coded to write out HTML (not even

Yes, the Tomcat layer can also produce error responses.

Did you try using an ExceptionMapper? in what cases did it not work
for you?

I forgot to mention an edge cases on mapping exceptions:

- when writing the response only the mapping of
WebApplicationException is performed, and only if the response has not
   committed (one or more bytes written).

perhaps that is a mistake and JAX-RS should relax it and any exception
can be mapped if the response has not been committed?