Search code examples
javajerseyguice

How do I use a Jersey ExceptionMapper with Google Guice?


I am using Jersey Guice and need to configure a custom ExceptionMapper

My module looks like this:

public final class MyJerseyModule extends JerseyServletModule
{
   @Override
   protected void configureServlets()
   {
      ...
      filter("/*").through(GuiceContainer.class);
      ...
   }
}

And this is my ExceptionMapper:

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

public class MyExceptionMapper implements ExceptionMapper<MyException>
{
   @Override
   public Response toResponse(final MyException exception)
   {
      return Response.status(Status.NOT_FOUND).entity(exception.getMessage()).build();
   }
}

Solution

  • Your ExceptionMapper must be annotated with @Provider and be a Singleton.

    import com.google.inject.Singleton;
    
    import javax.ws.rs.core.Response;
    import javax.ws.rs.core.Response.Status;
    import javax.ws.rs.ext.ExceptionMapper;
    import javax.ws.rs.ext.Provider;
    
    @Provider
    @Singleton
    public class MyExceptionMapper implements ExceptionMapper<MyException>
    {
       @Override
       public Response toResponse(final MyException exception)
       {
          return Response.status(Status.NOT_FOUND).entity(exception.getMessage()).build();
       }
    }
    

    Then just bind the ExceptionMapper in one of the Guice modules in the same Injector where your JerseyServletModule, and Jersey Guice will find it automatically.

    import com.google.inject.AbstractModule;
    
    public class MyModule extends AbstractModule
    {
       @Override
       protected void configure()
       {
          ...
          bind(MyExceptionMapper.class);
          ...
       }
    }
    

    You can also directly bind it in the JerseyServletModule if you want to:

    public final class MyJerseyModule extends JerseyServletModule
    {
       @Override
       protected void configureServlets()
       {
          ...
          filter("/*").through(GuiceContainer.class);
          bind(MyExceptionMapper.class);
          ...
       }
    }