2016-10-31 143 views
0

我想为我的cxf客户端使用ResponseExceptionMapper类来处理异常。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客户端中的异常。

有人可以帮助这个。

回答

1

您是如何将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; 
    } 
}