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).
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();
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.
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)
}