本文介绍了如何在Google Guice中使用Jersey ExceptionMapper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Jersey Guice,需要配置自定义ExceptionMapper
I am using Jersey Guice and need to configure a custom 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.
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();
}
}
然后将ExceptionMapper
绑定到与JerseyServletModule
相同的Injector
中的一个Guice模块中,然后Jersey Guice会自动找到它.
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);
...
}
}
如果需要,还可以将其直接绑定到JerseyServletModule
中:
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);
...
}
}
这篇关于如何在Google Guice中使用Jersey ExceptionMapper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!