How to get response body when testing the status code in WebFlux WebClient?

You could achieve like this by having a custom ExchangeFilterFunction and then hooking this up with WebClient.Builder before you build WebClient.

public static ExchangeFilterFunction errorHandlingFilter() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            if(clientResponse.statusCode()!=null && (clientResponse.statusCode().is5xxServerError() || clientResponse.statusCode().is4xxClientError()) ) {
                 return clientResponse.bodyToMono(String.class)
                         .flatMap(errorBody -> {
                             return Mono.error(new CustomWebClientResponseException(errorBody,clientResponse.statusCode()));
                             });
            }else {
                return Mono.just(clientResponse);
            }
        });
    }

You can use the above like this:

WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(clientOptions))
                .defaultHeader(HttpHeaders.USER_AGENT, "Application")
                .filter(WebClientUtil.errorHandlingFilter())
                .baseUrl("https://httpbin.org/")
                .build()
                .post()
                .uri("/post")
                .body(BodyInserters.fromObject(customObjectReference) )
                .exchange()
                .flatMap(response -> response.toEntity(String.class) );

So any 4XX or 5XX HttpResponse will actually throw CustomWebClientResponseException and you can configure some global exception handler and do what you like to with this. Atleast using ExchangeFilterFunction you can have global place to handle things like this or add custom headers and stuff too.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)