Search code examples
javaspring-webfluxproject-reactorspring-webclientspring-retry

Spring Web Client - How to get response string of failed request wrapped intro retrials


A little background

I would like to call service's APIs, while doing retries on 5xx errors. Also, I would like to get an access to every failed request (for logging purposes).

Code

getClient()
     .get()
     .uri("http://example.com")
     .retrieve()
     .onStatus(HttpStatus::is5xxServerError, rsp -> Mono.error(new ApiServerException("Server error", rsp.rawStatusCode())))
     .bodyToMono(ReportListResponse.class)
     .retryWhen(
          Retry
               .backoff(3, Duration.ofSeconds(1))
               .filter(throwable -> throwable instanceof ApiServerException)
     )
     .block();

Issue

How can I achieve the goal of being able to access the response of every failed request? I was trying to retrieve the body while using rsp.bodyToMono(String.class) in onStatus method. Unfortunately it didn't give me an expected output.


Solution

  • You would need to use response.bodyToMono in the onStatus to get response body. The following example shows how to deserialize body into String but you could define POJO as well.

    getClient()
            .get()
            .uri("http://example.com")
            .retrieve()
            .onStatus(HttpStatus::isError, response ->
                    response.bodyToMono(String.class)
                            .doOnNext(responseBody ->
                                    log.error("Error response from server: {}", responseBody)
                            )
                            // throw original error
                            .then(response.createException())
            )
            .bodyToMono(ReportListResponse.class)
        }