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