[英]Empty body when response has error status (Apache CXF)
Imagine there is a rest endpoint listening on host.tld/api
and which returns a 404 Not Found
with the following body:想象一下,有一个 rest 端点正在监听
host.tld/api
,它返回一个404 Not Found
并带有以下正文:
{
"status": 404,
"message": "This is a custom error message",
"errorNr": 13400
}
Additionally there is a ClientResponseFilter which looks like this:此外,还有一个 ClientResponseFilter,如下所示:
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
if (responseContext.getStatus() != Response.Status.OK.getStatusCode()) {
// get the real error message
CustomExceptionData error = new ObjectMapper().readValue(
responseContext.getEntityStream(),
CustomExceptionData .class
);
throw new CustomException(error.getErrorNr(), error.getStatus(), error.getMessage());
}
}
The client uses this code to retrieve the response of the rest endpoint:客户端使用此代码检索 rest 端点的响应:
WebTarget target = getTarget();
try {
return target.request(MediaType.APPLICATION_JSON_TYPE).get(MyCustomDTO.class);
} catch (Exception e) {
if (e.getCause() instanceof CustomException) {
// some other logic
}
}
The code must work with the jersey and the apache cxf JAX-RS implementation.该代码必须与 jersey 和 apache cxf JAX-RS 实现一起使用。 Now take a look at the last code block.
现在看看最后一个代码块。 When using jersey I get a
javax.ws.rs.ProcessingException
and executing e.getCause()
returns a CustomException
, so everything is correct.使用 jersey 时,我得到一个
javax.ws.rs.ProcessingException
并执行e.getCause()
返回一个CustomException
,所以一切都是正确的。 When using Apache CXF I get a javax.ws.rs.NotFoundException
with absolutely no information about the response body and where e.getCause()
returns null
.使用 Apache CXF 时,我得到一个
javax.ws.rs.NotFoundException
,其中完全没有关于响应主体的信息,并且e.getCause()
在哪里返回null
。 Why is there such a difference?为什么会有这样的差异? And how can I fix that?
我该如何解决?
Just before you throw your exception, you can set the status code to 200, which will prevent CXF from throwing a NotFoundException
:就在您抛出异常之前,您可以将状态码设置为 200,这将防止 CXF 抛出
NotFoundException
:
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
if (responseContext.getStatus() != Response.Status.OK.getStatusCode()) {
// get the real error message
CustomExceptionData error = new ObjectMapper().readValue(
responseContext.getEntityStream(),
CustomExceptionData .class
);
responseContext.setStatus(Response.Status.OK.getStatusCode());
throw new CustomException(error.getErrorNr(), error.getStatus(), error.getMessage());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.