Mapping exceptions to Response in JAX-RS

In JAX-RS, we can map exceptions to a Response. This will be useful in hiding the exceptions from the client of JAX-RS web services.

Below is an example showing how to map exceptions to appropriate responses.

First we need to implement ExceptionMapper interface as shown below. Here we want to map NullPointer exception to Internal server error response. So we name the class as NullPointerExceptionMapper.


1  package resource;
3  import;
4  import;
5  import;
7  @Provider
8  public class NullPointerExceptionMapper implements ExceptionMapper {
9   @Override
10  public Response toResponse(NullPointerException arg0) {
11      return Response.serverError().build();
12  }
13 }

From the above code, the class NullPointerExceptionMapper implements ExceptionMapper interface. We need to provide an implementation of toResponse method.

From the above code, in the method we create and return Response object with server error as status code.

At line 7 we annotate the class with Provider annotation.

The code of the resource class throwing the NullPointerException is as shown below

Resource class

package resource;


public class WebResource9 {
    public Response exception() {
        throw new NullPointerException();

When you access the resource using the url

you will get response as Internal server error instead of exception.

Leave a Reply