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.

NullPointerExceptionMapper


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

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;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("webresource9")
public class WebResource9 {
    @GET
    @Path("exception")
    public Response exception() {
        throw new NullPointerException();
    }
}

When you access the resource using the url
http://localhost:8080/JAXRSConcepts/myresources/webresource9/exception

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

Leave a Reply