cxf客户端中的ResponseExceptionMapper [英] ResponseExceptionMapper in cxf client
问题描述
我正在尝试为我的cxf客户端使用ResponseExceptionMapper类来处理异常。
I am trying to handle exceptions using the ResponseExceptionMapper class for my cxf client.
ExceptionHandlingCode:
public class MyServiceRestExceptionMapper implements ResponseExceptionMapper<Exception> {
private static final Logger LOGGER = LoggerFactory.getLogger(MyServiceRestExceptionMapper .class);
public MyServiceRestExceptionMapper () {
}
@Override
public Exception fromResponse(Response response) {
LOGGER.info("Executing MyServiceRestExceptionMapper class");
Response.Status status = Response.Status.fromStatusCode(response.getStatus());
LOGGER.info("Status: ", status.getStatusCode());
switch (status) {
case BAD_REQUEST:
throw new InvalidServiceRequestException(response.getHeaderString("exception"));
case UNAUTHORIZED:
throw new AuthorizationException(response.getHeaderString("exception"));
case FORBIDDEN:
throw new AuthorizationException(response.getHeaderString("exception"));
case NOT_FOUND:
throw new
EmptyResultDataAccessException(response.getHeaderString("exception"));
default:
throw new InvalidServiceRequestException(response.getHeaderString("exception"));
}
}
}
CXF客户端代码:
String url1=
WebClient client = createWebClient(url1).path(/document);
client.headers(someHeaders);
Response response = client.post(byteArry);
对于成功方案,我得到正确的响应代码200,但是对于失败方案,我从来没有得到响应代码。
For success scenarios, I am getting the correct response code of 200, but for failure scenarios, I never get a response code.
还有在cxf客户端中处理异常的更好方法。
Also is there a better way of handling exceptions in cxf client.
有人请帮忙。
推荐答案
您如何将 ResponseExceptionMapper
注册到
您需要这样的东西
List<Object> providers = new ArrayList<Object>();
providers.add(new MyServiceRestExceptionMapper()
WebClient client = WebClient.create(url, providers);
我建议使用 WebApplicationException
代替 Exception
,因为默认行为会引发此类异常如果没有注册 ResponseExceptionMapper
,也请返回该异常,不要抛出该异常。映射器应如下所示。
I suggest to use a WebApplicationException
insteadof Exception
because default behaviour will raise this kind of exception if no ResponseExceptionMapper
is registered. Also, return the exception, do not throw it. The exception mapper should looks like this.
public class MyServiceRestExceptionMapper implements ResponseExceptionMapper<WebApplicationException>
public MyServiceRestExceptionMapper () {
}
@Override
public WebApplicationException fromResponse(Response response) {
//Create your custom exception with status code
WebApplicationException ex = ...
return ex;
}
}
这篇关于cxf客户端中的ResponseExceptionMapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!