Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a Jersey ExceptionMapper with Google Guice?

Tags:

java

jersey

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();
   }
}
like image 621
lexicalscope Avatar asked Aug 16 '12 12:08

lexicalscope


1 Answers

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);
      ...
   }
}
like image 195
lexicalscope Avatar answered Dec 22 '22 04:12

lexicalscope