How to use Jersey ExceptionMapper with Google Guice?

I am using Jersey Guice and you need to set up a custom ExceptionMapper

My module is as follows:

 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(); } } 
+7
source share
1 answer

Your ExceptionMapper should be annotated with @Provider and be 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 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 link it in the JerseyServletModule if you want:

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

All Articles