This article relies on the code and some of the explanation from the following articles, be sure to go over those first:
- A custom exception mapper and writer for a RESTful JAX-RS Jersey service
- Jersey JAX-RS filters and interceptors execution order for a POST request
- Jersey JAX-RS filters and interceptors execution order for a simple GET request
I am not covering the execution order prior to getting to the Resource class as that's been covered in the previous articles I've written (linked above) and since it varies depending on whether you use GET or POST methods and if any message body readers are used.
So lets see what happens when a request is made to the /exception URI of the service that's been built up so far...
Since the Resource class in this case simply throws a HelloException, execution shifts straight to the ExceptionMapper. Then the container response filter and writer interceptor are called. Behaviour after this point depends on how the exception mapper is implemented.
I've implemented two versions of the exception mapper, one that used a standard String entity and one that used the actual HelloException as the entity itself. The latter version meant that an entity writer (message body writer) is used to transform the exception (entity) into output from the service. If the Exception is used as the entity, the message body writer is invoked, otherwise nothing further from your service is called.
The execution order is quite straight forward for cases where an exception is thrown from your Resource code, and can be very powerful. This approach can be used to catch and process exceptions and to generate valid responses from your service, instead of simply letting Jersey return the usual 500 error.
-i