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

1

1

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.

Lennalennard answered 11/4, 2022 at 11:46 Comment(0)
T
1

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)
    }
Trehala answered 12/4, 2022 at 5:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.