想象有一个休息的端点正在监听,host.tld/api
并且返回404 Not Found
带有以下内容的:
{
"status": 404,
"message": "This is a custom error message",
"errorNr": 13400
}
另外,还有一个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());
}
}
客户端使用以下代码检索其余端点的响应:
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
}
}
该代码必须与jersey和apache cxf JAX-RS实现一起使用。现在看一下最后一个代码块。使用jersey时,我得到a javax.ws.rs.ProcessingException
并执行e.getCause()
返回a CustomException
,所以一切正确。使用Apache CXF时,我得到的消息javax.ws.rs.NotFoundException
绝对没有有关响应正文和e.getCause()
返回位置的信息null
。为什么会有这样的差异?我该如何解决?
在引发异常之前,可以将状态代码设置为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());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句