我正在使用Jersey Guice,需要配置自定义ExceptionMapper
我的模块如下所示:

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

这是我的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();
   }
}

最佳答案

您的ExceptionMapper必须使用@Provider注释,并且必须是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();
   }
}

然后,将ExceptionMapper绑定(bind)到您的Injector相同的JerseyServletModule中的Guice模块之一中,Jersey Guice会自动找到它。
import com.google.inject.AbstractModule;

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

如果您要执行以下操作,也可以将其直接绑定(bind)到JerseyServletModule中:
public final class MyJerseyModule extends JerseyServletModule
{
   @Override
   protected void configureServlets()
   {
      ...
      filter("/*").through(GuiceContainer.class);
      bind(MyExceptionMapper.class);
      ...
   }
}

07-26 07:30