ResponseExceptionMapper

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客户端中的异常。

有人可以帮忙吗?

最佳答案

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

09-04 11:48