Как установить onStatus в экземпляре конструктора Spring WebClient

У меня много методов, которые используют onStatus API из Spring WebClient:

@Override
public Mono<Accommodation> createAccommodation(CreateAccommodation create) {
    return webClient
            .post()
            .contentType(APPLICATION_JSON)
            .bodyValue(create)
            .retrieve()
            .onStatus(HttpStatus::isError,
                    clientResponse -> clientResponse
                            .bodyToMono(ApiErrorResponse.class)
                            .flatMap(errorResponse -> Mono.error(new ResponseStatusException(
                                    HttpStatus.valueOf(errorResponse.getStatus()),
                                    errorResponse.getMessage()
                            ))))
            .bodyToMono(Accommodation.class);
}

Я бы хотел избежать использования «onStatus» в каждом отдельном вызове WebClient.

Есть ли способ установить это при создании экземпляра WebClient? Вы можете показать несколько примеров?

Это мой экземпляр WebClient:

    public AccommodationServiceClientImpl(WebClient.Builder builder) {
         this.webClient = builder
            .baseUrl("lb://accommodation-service/api/v1/accommodations")
            .build();
    }

person damsen    schedule 07.05.2020    source источник
comment
Поскольку извлечение возвращает частный внутренний класс в Webclient, вам придется расширить Webclient своей собственной версией, которая переопределяет retrieve(), и заставить его возвращать вашу собственную версию ResponseSpec.   -  person 123    schedule 07.05.2020
comment
На самом деле похоже, что все классы в этом пакете по какой-то причине являются частными, поэтому не думайте, что вы можете ...   -  person 123    schedule 07.05.2020


Ответы (1)


Нашел решение: ExchangeFilterFunction.ofResponseProcessor, похоже, то, что я искал.

@Configuration
public class WebClientConfig {

    @Bean
    @LoadBalanced
    public WebClient.Builder webClientBuilder(){
        return WebClient
                .builder()
                .filter(ExchangeFilterFunction.ofResponseProcessor(this::renderApiErrorResponse));
    }

    private Mono<ClientResponse> renderApiErrorResponse(ClientResponse clientResponse) {
        if(clientResponse.statusCode().isError()){
            return clientResponse.bodyToMono(ApiErrorResponse.class)
                    .flatMap(apiErrorResponse -> Mono.error(new ResponseStatusException(
                            clientResponse.statusCode(),
                            apiErrorResponse.getMessage()
                    )));
        }
        return Mono.just(clientResponse);
    }

}
person damsen    schedule 07.05.2020