I am using the Spring WebFlux webclient to make REST calls. I've configured the connection timeout on 3000
milliseconds, accordingly:
WebClient webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(options -> options
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)))
.build();
return webClient.get()
.uri("http://localhost:8081/resource")
.retrieve()
.onStatus(HttpStatus::isError, clientResponse -> {
// Some logging..
return Mono.empty();
})
.bodyToMono(MyPojo.class);
The onStatus
method is returning an empty Mono
for every 400
/ 500
response code. How can I do the same for a connection timeout and maybe even read / write timeouts. As right now its just throwing a io.netty.channel.ConnectTimeoutException
which is not handled by the onStatus
I don't need an @ExceptionHandler
on my controller, as these REST calls are part of a more complex flow, and via an empty Mono
the element should just be ignored.
Back in spring-web
with a RestTemplate
, I remember the connection timeout also resulted in a RestClientException
. So we could just catch the RestClientException
for all exceptions and timeouts. Is there a way we can do this with WebClient
as well?
Reactor offers multiple onError***
operators for this:
return webClient.get()
.uri("http://localhost:8081/resource")
.retrieve()
.onErrorResume(ex -> Mono.empty())
.onStatus(HttpStatus::isError, clientResponse -> {
// Some logging..
return Mono.empty();
})
.bodyToMono(MyPojo.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With