How do I use a Jersey ExceptionMapper with Google Guice?

喜欢而已 提交于 2019-12-04 19:17:24

问题


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();
   }
}

回答1:


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


来源:https://stackoverflow.com/questions/11987097/how-do-i-use-a-jersey-exceptionmapper-with-google-guice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!