是否有与RestTemplate类似的DefaultResponseErrorHandler功能?

时间:2018-05-02 20:34:03

标签: spring spring-webflux

我在公司内部维护的库提供了DefaultResponseErrorHandler的自定义实现,我们通过RestTemplateCustomizer分配。此实现查看响应的实际http状态代码并进行翻译。

基本上我们的课程重写

@Override
protected void handleError(ClientHttpResponse response, HttpStatus statusToReturn) throws IOException {
  super.handleError(response, someOtherStatusThatIsComputedInternally);
}

我们只是传递一个不同的状态代码,Spring会负责创建相应的HttpClientErrorException / HttpServerErrorException

我尝试使用WebClientExchangeFilterFunction中复制此功能(并通过WebClientCustomizer注入),但我不太清楚如何获取在它,因为ClientResponse.statusCode()已经设置并且无法被覆盖,我似乎无权覆盖WebClientResponseException的创建。

任何想法/提示?

1 个答案:

答案 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;
    }
}