Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring WebFlux webclient handle ConnectTimeoutException

Tags:

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?

like image 338
Dennis Nijssen Avatar asked Mar 10 '18 09:03

Dennis Nijssen


1 Answers

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);
like image 66
Brian Clozel Avatar answered Sep 22 '22 12:09

Brian Clozel