我想将underlaying包装RuntimeExceptions为自定义json格式,使servlet容器不会将stacktrace转储到客户端.
我遵循这个问题:使用XML或JSON的JAX-RS(Jersey)自定义异常.致电时:
try {
doSomething(parameters);
}
catch(RuntimeException e) {
throw new MyCustomException(500 , e.getMessage() , Status.INTERNAL_SERVER_ERROR);
}
Run Code Online (Sandbox Code Playgroud)
当我故意输入错误的参数(并触发RuntimeException引发doSomething())时,我没有看到MyCustomExceptionMapper工作.相反,servlet容器转储:
The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
api.MyCustomException: (underlaying msgs)
Run Code Online (Sandbox Code Playgroud)
该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;
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么 ?
非常感谢 !
环境:JAX-RS,泽西服务器1.5
课程规格:
class MyCustomException extends RuntimeException
@Provider
class MyCustomExceptionMapper implements ExceptionMapper<MyCustomException>
Run Code Online (Sandbox Code Playgroud)
更新:
我怀疑Application.getClasses()从未调用过,所以我添加了一些println消息:
@Override
public Set<Class<?>> getClasses()
{
System.out.println("\n\n\n\n ApiConfig getClasses");
}
Run Code Online (Sandbox Code Playgroud)
并且在行动中,它从未显示过!
我确定这个ApiConfig在web.xml中:
<context-param>
<param-name>javax.ws.rs.core.Application</param-name>
<param-value>destiny.web.api.ApiConfig</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)
但是为什么泽西岛似乎从来没有称之为呢
我找到了解决方案。
我所要做的就是用 Spring 的@Repository.
并删除 web.xml 中的部分(不需要)
<context-param>
<param-name>javax.ws.rs.core.Application</param-name>
<param-value>destiny.web.api.ApiConfig</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)
因为 Spring 会查找所有 @Repository 并找到一个 @Provider ,而 Jersey 会利用它。
| 归档时间: |
|
| 查看次数: |
15367 次 |
| 最近记录: |