Skip to content
Mihail Kuznetsov edited this page Mar 16, 2015 · 2 revisions

Exception handling

Exception handling

JAX-RS specification providers interface ExceptionMapper to customise exception handing. Implementation of such interface should be able transform exception to specific HTTP response. ExceptionMappers must be annotated with @Provider annotation. ExceptionMappers are inherited, it minds if mapper for RuntimeException registred then it may be used to process all exceptions which extend RuntimeException and does not have own mapper. Here is example of implementation of ExceptionMapper that you can find in EverRest samples in subversion repository:

package org.everrest.sample.book;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class BookNotFoundExceptionMapper implements ExceptionMapper<BookNotFoundException>
{
   public Response toResponse(BookNotFoundException exception)
   {
      return Response.status(404).entity(exception.getMessage()).type("text/plain").build();
   }
}

It transforms BookNotFoundException to response with HTTP status 404. The resource class may be as following:

@Path("books")
public class BookService
{
   @Inject
   private BookStorage bookStorage;

   @Path("{id}")
   @GET
   @Produces("application/json")
   public Book get(@PathParam("id") String id) throws BookNotFoundException
   {
      Book book = bookStorage.getBook(id);
      if (book == null)
         throw new BookNotFoundException(id);
      return book;
   }
...
}

EverRest has embedded ExceptionMapper that process all exceptions if they have not own mappers:

public class DefaultExceptionMapper implements ExceptionMapper<Exception>
{
   public Response toResponse(Exception exception)
   {
      String message = exception.getMessage();
      if (message == null)
         message = exception.getClass().getName();
      return Response.status(500).entity(message).type(MediaType.TEXT_PLAIN).build();
   }
}

You are also able to use javax.ws.rs.WebApplicationException to deliver correct HTTP response to client. Here is example of usage WebApplicationException:

@Path("books")
public class BookService
{
   @Inject
   private BookStorage bookStorage;

   @Path("{id}")
   @GET
   @Produces("application/json")
   public Book get(@PathParam("id") String id)
   {
      Book book = bookStorage.getBook(id);
      if (book == null)
         throw new WebApplicationException(Response.status(404)
            .entity("Book with id " + id + " not found.")
            .type(MediaType.TEXT_PLAIN).build());
      return book;
   }
...
}