我在公司内部维护的库提供了DefaultResponseErrorHandler
的自定义实现,我们通过RestTemplateCustomizer
分配。此实现查看响应的实际http状态代码并进行翻译。
基本上我们的课程重写
@Override
protected void handleError(ClientHttpResponse response, HttpStatus statusToReturn) throws IOException {
super.handleError(response, someOtherStatusThatIsComputedInternally);
}
我们只是传递一个不同的状态代码,Spring会负责创建相应的HttpClientErrorException
/ HttpServerErrorException
。
我尝试使用WebClient
在ExchangeFilterFunction
中复制此功能(并通过WebClientCustomizer
注入),但我不太清楚如何获取在它,因为ClientResponse.statusCode()
已经设置并且无法被覆盖,我似乎无权覆盖WebClientResponseException
的创建。
任何想法/提示?
答案 0 :(得分:0)
我能够使用Spring提供的内置ClientResponseWrapper
做我需要做的事情。
在ExchangeFilterFunction
我这样做:
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(request).flatMap(this::handleAnyErrors);
}
private Mono<ClientResponse> handleAnyErrors(ClientResponse response) {
HttpStatus actualHttpStatus = response.statusCode();
HttpStatus statusToReturn = getActualStatusCodeWeWantToReturn();
return Mono.just((actualHttpStatus != statusToReturn) ? new ClientResponseStatusCodeWrapper(response, statusToReturn) : response);
}
private static class ClientResponseStatusCodeWrapper extends ClientResponseWrapper {
private final HttpStatus httpStatus;
private ClientResponseStatusCodeWrapper(ClientResponse delegate, HttpStatus httpStatus) {
super(delegate);
this.httpStatus = httpStatus;
}
@Override
public HttpStatus statusCode() {
return this.httpStatus;
}
}