6

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?

1
  • I tried your code, but I get a NullPointerException if I return Mono.empty(). Did that really work for you? The documentation says that you have to throw an exception instead of returning Mono.empty(). Commented Nov 8, 2018 at 11:26

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Why don't return Mono.error() instead of Mono.empty() ?
That is what the OP asked about at the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.