![](/img/trans.png)
[英]JAX-RS CXF: How to get Exception from ResponseExceptionMapper
[英]ResponseExceptionMapper in cxf client
我正在嘗試為我的cxf客戶端使用ResponseExceptionMapper類來處理異常。
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,但是對於失敗方案,我從未得到響應代碼。
還有一種更好的方法來處理cxf客戶端中的異常。
有人可以幫忙嗎?
您如何將ResponseExceptionMapper
注冊到WebClient?
你需要這樣的東西
List<Object> providers = new ArrayList<Object>();
providers.add(new MyServiceRestExceptionMapper()
WebClient client = WebClient.create(url, providers);
我建議使用WebApplicationException
不是Exception
因為如果未注冊ResponseExceptionMapper
則默認行為將引發此類異常。 同樣,返回異常,不要拋出該異常。 異常映射器應如下所示。
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.