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); ... } }
lexicalscope
source share