Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I've written quite a few articles about Jersey already ranging from filter and interceptor execution order to a custom message body reader implementation. This article delves deeper into Jersey and looks at how to gracefully handle exceptions by using an exception mapper and entity writer to convert a caught exception to output from your service.

First lets define a custom exception we'll be throwing. It's not strictly required to have a custom exception but for the purposes of this article it makes it easier to see what's going on if we do. The class itself is not remarkable and is as simple as it can get really...
public class HelloException extends Exception {
public HelloException(String msg) {

Next we need a resource class that throws this exception. The class implements a simple GET method on the /exception URI and throws a new HelloException with the message "Hello!" Again nothing remarkable - just demo code.
@Produces({ "text/plain" })
public class HelloExceptionResource {
public String throwException()
throws HelloException
throw new HelloException("Hello!");

If the service is invoked at this point the output will be "Request failed." like shown in the screenshot below...

Jersey will also emit a ServletException with the cause set to HelloException to the WebLogic standard output. This isn't exactly graceful nor the result we want, so read on.
 WebLogic standard out
<09/11/2017 8:25:41,574 PM AEDT> <Error> <HTTP> <BEA-101017> <[[email protected][app:JerseyServiceRS module:JerseyServiceRS.war path:null spec-version:3.1], request: [email protected][
GET /JerseyServiceRS/Service/exception HTTP/1.1
cache-control: no-cache
Postman-Token: e9d8916a-bcc7-4216-a9ce-7030d774403b
User-Agent: PostmanRuntime/6.4.1
Accept: */*
accept-encoding: gzip, deflate
Connection: keep-alive
]] Root cause of ServletException.
org.glassfish.jersey.server.ContainerException: net.igorkromin.HelloException: Hello!
at org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:278)
at org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:260)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:509)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:334)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
Truncated. see log file for complete stacktrace
Caused By: net.igorkromin.HelloException: Hello!
at net.igorkromin.HelloExceptionResource.throwException(HelloExceptionResource.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
Truncated. see log file for complete stacktrace

To stop the ServletException being thrown we can add a very simple ExceptionMapper implementation for the HelloException class. With this in place, Jersey will use the Response from the implementation of this class instead of its default. This implementation uses a String entity with "ERROR: " appended to the exception message. The HTTP response status is set to 500.
public class HelloExceptionMapper implements ExceptionMapper<HelloException> {
public Response toResponse(HelloException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity("ERROR: " + e.getMessage()).

Making the same GET request again results in different behaviour now. We get this message back - "ERROR: Hello!" Nothing is logged by Jersey or WebLogic either - since the exception mapper implementation doesn't do any logging.

That first implementation is a step forward but we can do better. Instead of relying on Jersey to generate output from the String entity we can use a message body writer to convert HelloException to data on the Response output stream.

First the return statement in the exception mapper must be modified to this:
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).

This sets the entity to the HelloException instance itself. Then we add this body writer that will match write requests for HelloException...
public class HelloExceptionWriter implements MessageBodyWriter<HelloException> {
public boolean isWriteable(Class<?> aClass, Type type,
Annotation[] annotations, MediaType mediaType) {
return (type == HelloException.class);
public long getSize(HelloException e, Class<?> aClass, Type type,
Annotation[] annotations, MediaType mediaType) {
/* deprecated by JAX-RS 2.0 and ignored by Jersey runtime */
return 0;
public void writeTo(HelloException e, Class<?> aClass, Type type,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream outputStream)
throws IOException, WebApplicationException {
try (BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(outputStream));
PrintStream ps = new PrintStream(outputStream)) {
bw.write("ERROR: " + e.getMessage() + "\n");

The body writer implements three methods - isWriteable(), getSize() and writeTo(). The isWriteable() method simply makes sure this writer is being used to write a HelloException class. The getSize() method is not used. The writeTo() method is where all the real action happens.

In the writeTo() method we create a BufferedWriter and a PrintStream and then write a String to the buffered writer, then flush it. Afterwards the stack trace for the exception is written to the print stream. Nothing complicated here, just outputting the exception to the output stream. This ends up as output from your service and looks like this...

The body writer is quite simple in this case but serves to show how exceptions can be handled and written to the output of a service. In more complex scenarios this approach can be used to convert exceptions to JSON objects or even to generate a custom response message from your service.

Don't forget to register() the above classes in your ResourceConfig implementation or add the @Provider annotation if you're using automatic feature discovery to make all this work.

If you want to know where the exception mapper fits into the execution order in Jersey, see this article - Jersey JAX-RS filters and interceptors execution order when throwing Exceptions.


Have comments or feedback on what I wrote? Please share them below!
comments powered by Disqus
Other posts you may like...