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...
 HelloException.java
public class HelloException extends Exception {
public HelloException(String msg) {
super(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.
 HelloExceptionResource.java
@Path("/exception")
@Produces({ "text/plain" })
public class HelloExceptionResource {
@GET
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_ex1.png


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.
 HelloExceptionMapper.java
public class HelloExceptionMapper implements ExceptionMapper<HelloException> {
@Override
public Response toResponse(HelloException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity("ERROR: " + e.getMessage()).
build();
}
}


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.
jersey_ex2.png


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:
 Java
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity(e).
build();


This sets the entity to the HelloException instance itself. Then we add this body writer that will match write requests for HelloException...
 HelloExceptionWriter.java
public class HelloExceptionWriter implements MessageBodyWriter<HelloException> {
@Override
public boolean isWriteable(Class<?> aClass, Type type,
Annotation[] annotations, MediaType mediaType) {
return (type == HelloException.class);
}
@Override
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;
}
@Override
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");
bw.flush();
e.printStackTrace(ps);
}
}
}



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...
jersey_ex3.png


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.

-i

Please leave your comments or feedback below!
comments powered by Disqus
Other posts you may like...
Hi! You can search my blog here ⤵
Or browse the recent top tags...

Recent Blog Posts

Using DeoxIT to repair old game catridges

WebLogic Maven Plugin - How to fix the MojoExecutionException: The artifact location was not specified

jPhotoFrame version 0.4 released with a whole new layout engine

Upcycling a couple of old broken lamps to create something amazing

A custom exception mapper and writer for a RESTful JAX-RS Jersey service

How to fix Plex error - Sorry there was a problem playing this item

Jersey JAX-RS filters and interceptors execution order for a POST request

Fix your Mac - users not showing on the macOS login screen when FileVault is enabled

BMB-012 Nanoblock T-Rex Skeleton Model assembly

Writing a custom MessageBodyReader to process POST body data with Jersey

Recent Galleries

BMB-012 Nanoblock T-Rex Skeleton Model assembly

Tiny Arcade revision 6 kit assembly and decal application

Atari Lynx repair - Part 5 - McWill LED screen mod installation

Atari Lynx repair - Part 4 - screen cover replacement

Atari Lynx repair - Part 2 - re-capping the motherboard

Atari Lynx repair - Part 3 - broken speaker replacement

Atari Lynx repair - Part 1 - introduction and case disassembly

Building a custom Atari Lynx game box storage shelf unit in a day

Protecting old Atari Lynx game boxes with snug fit plastic sleeves

Monument Valley 2 is released and does not disappoint

Blogs and Friends

Matt Moores Blog
Georgi's FlatPress Guide
Perplexing Permutations
The Security Sleuth
Ilia Rogatchevski
Travelling Fairy

Blog Activity

Blog Activity