I need to make another HTTP call in the case that my WebClient request receives a HTTP 4xx or 5xx error.
Currently I have the following:
webClient.post()
.uri(myUri)
.headers(myHeaders)
.body(myBody)
.retrieve()
.onStatus(HttpStatus::isError, responseStrategy::errorResponseCallback)
...
My error response callback looks like this:
public Mono<? extends Throwable> errorResponseCallback(ClientResponse clientResponse) {
... make ugly new HTTP request here
return Mono.error(...);
}
I don't like the idea of embedding error handling in the callback which is only supposed to return a Mono containing an exception.
What is the correct approach for this situation?
In case you want to simulate some fallback
-based logic, you may use onErrorResume
method and the fallback function result will be passed to the downstream. The WebClient will threat non-successful results as errors, so onErrorResume
is called.
webClient.post()
.uri(myUri)
.headers(myHeaders)
.body(myBody)
.retrieve()
.bodyToMono(String.class)
.onErrorResume(error -> ... your fallback logic ...)
In case you just want to perform some side-effect, and you want to keep the error to go through the reactive stream, you may use:
webClient.post()
.uri(myUri)
.headers(myHeaders)
.body(myBody)
.retrieve()
.bodyToMono(String.class)
.doOnError(error -> ... your fallback logic ...)