我开始在JAX-RS中使用新的客户端API库,并且到目前为止真的非常喜欢它.我找到了一件我无法弄清楚的事情.我使用的API有一个自定义错误消息格式,例如:
{
"code": 400,
"message": "This is a message which describes why there was a code 400."
}
Run Code Online (Sandbox Code Playgroud)
它返回400作为状态代码,但还包含一条描述性错误消息,告诉您错误.
但是,JAX-RS 2.0客户端将400状态重新映射到通用的状态,我丢失了良好的错误消息.它正确地将它映射到BadRequestException,但具有通用的"HTTP 400 Bad Request"消息.
javax.ws.rs.BadRequestException: HTTP 400 Bad Request
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:908)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:770)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:424)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:396)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:296)
Run Code Online (Sandbox Code Playgroud)
是否有某种拦截器或自定义错误处理程序可以注入,以便我可以访问真正的错误消息.我一直在查看文档,但看不到任何方法.
我现在正在使用Jersey,但是我尝试使用CXF并得到了相同的结果.这是代码的样子.
Client client = ClientBuilder.newClient().register(JacksonFeature.class).register(GzipInterceptor.class);
WebTarget target = client.target("https://somesite.com").path("/api/test");
Invocation.Builder builder = target.request()
.header("some_header", value)
.accept(MediaType.APPLICATION_JSON_TYPE)
.acceptEncoding("gzip");
MyEntity entity = builder.get(MyEntity.class);
Run Code Online (Sandbox Code Playgroud)
更新:
我实现了下面评论中列出的解决方案.它略有不同,因为类在JAX-RS 2.0客户端API中有所改变.我仍然认为默认行为是提供一般错误消息并丢弃真实错误消息是错误的.我理解为什么它不会解析我的错误对象,但应该返回未解析的版本.我最终得到了库已经执行的复制异常映射.
谢谢您的帮助.
这是我的过滤器类:
@Provider
public …Run Code Online (Sandbox Code Playgroud)