11

我正在使用 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();
   }
}
4

1 回答 1

19

您的 ExceptionMapper 必须带有注释@Provider并且是单例。

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其中一个 Guice 模块绑定到Injector您的JerseyServletModule.Jersey Guice 会自动找到它。

import com.google.inject.AbstractModule;

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

JerseyServletModule如果你想,你也可以直接绑定它:

public final class MyJerseyModule extends JerseyServletModule
{
   @Override
   protected void configureServlets()
   {
      ...
      filter("/*").through(GuiceContainer.class);
      bind(MyExceptionMapper.class);
      ...
   }
}
于 2012-08-16T12:26:37.280 回答