问题描述
我想将底图RuntimeExceptions
包装为自定义json格式,从而使servlet容器不会将stacktrace转储到客户端.
I want to wrap underlaying RuntimeExceptions
to a custom json format , making the servlet container won't dump the stacktrace to client.
我关注这个问题: JAX-RS(泽西岛) XML或JSON的自定义异常.致电时:
I follow this question : JAX-RS (Jersey) custom exception with XML or JSON .When calling :
try {
doSomething(parameters);
}
catch(RuntimeException e) {
throw new MyCustomException(500 , e.getMessage() , Status.INTERNAL_SERVER_ERROR);
}
当我故意输入错误的参数(并触发了doSomething()
引发的RuntimeException
)时,我没有看到MyCustomExceptionMapper
起作用.取而代之的是,servlet容器转储:
When I intentionally feed wrong parameters (and trigger RuntimeException
thrown by doSomething()
) , I didn't see MyCustomExceptionMapper
working. Instead , the servlet container dumps :
The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
api.MyCustomException: (underlaying msgs)
MyCustomExceptionMapper
实际上已在javax.ws.rs.core.Application
中注册:
@Override
public Set<Class<?>> getClasses()
{
Set<Class<?>> set = new HashSet<Class<?>>();
set.add(other classes);
set.add(MyCustomExceptionMapper.class);
return set;
}
我想念什么?
非常感谢!
环境:JAX-RS,jersey-server 1.5
Environment : JAX-RS , jersey-server 1.5
分类说明:
class MyCustomException extends RuntimeException
@Provider
class MyCustomExceptionMapper implements ExceptionMapper<MyCustomException>
已更新:
我怀疑Application.getClasses()
从未被调用过,所以我添加了一些println消息:
I suspect that Application.getClasses()
is never called , so I add some println messages :
@Override
public Set<Class<?>> getClasses()
{
System.out.println("\n\n\n\n ApiConfig getClasses");
}
事实上,它从未显示!
我确定此ApiConfig位于web.xml中:
I am sure this ApiConfig is in the web.xml :
<context-param>
<param-name>javax.ws.rs.core.Application</param-name>
<param-value>destiny.web.api.ApiConfig</param-value>
</context-param>
但是为什么泽西似乎从来没有称呼它?
But why it seems Jersey never calls it ?
推荐答案
我找到了解决方案.
我要做的就是用Spring的@Repository
注释MyCustomExceptionMapper.
All I have to do is annotate MyCustomExceptionMapper with Spring's @Repository
.
并删除web.xml中的部分(不需要)
And remove the section in web.xml (not needed)
<context-param>
<param-name>javax.ws.rs.core.Application</param-name>
<param-value>destiny.web.api.ApiConfig</param-value>
</context-param>
因为Spring会查找所有@Repository并找到一个@Provider,Jersey会使用它.
Because Spring will lookup all @Repository and find a @Provider , and Jersey will make use of it.
这篇关于JAX-RS自定义ExceptionMapper无法拦截RuntimeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!