uri" /> uri" /> uri"/>

While using WebClient retryWhen is not executed when using exchangeToMono

39 Views Asked by At

As of now I'm building a request using WebClient as follows:

          Map<String, Object> apiResponse = this.webClient.get()
                .uri("/baseUri",
                        uriBuilder -> uriBuilder
                                .queryParam("sampleParam", "sampleValue")
                                .build()
                )
                .exchangeToMono(response -> {
                    if (response.statusCode() == HttpStatus.OK) {
                        return response.bodyToMono(Map.class);
                    }

                    // log error
                    return Mono.empty();
                })
                .retryWhen(Retry.fixedDelay(5, Duration.ofSeconds(5)))
                .block();

         if (apiResponse == null) { // Is this condition even required?
            return "";
         }

         ... code handling apiResponse ...

While testing it I'm only seeing the logging bit once when the endpoint is failing, is not even applying the retryWhen clause.

How should I manage errors, allowing retries but failing silently without throwing an exception? Are retryWhen and exchangeToMono mutually exclusive?

1

There are 1 best solutions below

0
amir rad On BEST ANSWER

This is how you can combine these operators to manage errors, allow retries, and handle failures without throwing exceptions:

Map<String, Object> apiResponse = this.webClient.get()
        .uri("/baseUri",
                uriBuilder -> uriBuilder
                        .queryParam("sampleParam", "sampleValue")
                        .build()
        )
        .exchangeToMono(response -> {
            if (response.statusCode() == HttpStatus.OK) {
                return response.bodyToMono(Map.class);
            }

            // Log error and retry logic
            return Mono.error(new RuntimeException("Non-OK status code"));
        })
        .retryWhen(Retry.fixedDelay(5, Duration.ofSeconds(5)))
        .onErrorResume(e -> {
            // Handle error silently without throwing exception
            return Mono.empty();
        })
        .block();

// Code handling apiResponse or handling empty response

if the response status code is not HttpStatus.OK, the operation will trigger a retry based on the retryWhen logic. If the retry fails or encounters an error, the onErrorResume operator handles the error silently without throwing an exception.