11

I am new to spring webclient and i have written a generic method which can be used to consume rest apis in my application:

public <T> List<T> get(URI url, Class<T> responseType) {
        return  WebClient.builder().build().get().uri(url)
                   .header("Authorization", "Basic " + principal)
                   .retrieve().bodyToFlux(responseType).collectList().block();
}

i wanted to return and empty list if consumed rest-api return 404.

can someone suggest how to achieve that?

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
Rohit Singh
  • 145
  • 1
  • 2
  • 7

3 Answers3

8

By default retrieve method throws WebClientResponseException exception for any 4xx & 5xx errors

By default, 4xx and 5xx responses result in a WebClientResponseException.

You can use onErrorResume

 webClient.get()
 .uri(url)
 .retrieve()
 .header("Authorization", "Basic " + principal)
 .bodyToFlux(Account.class)
 .onErrorResume(WebClientResponseException.class,
      ex -> ex.getRawStatusCode() == 404 ? Flux.empty() : Mono.error(ex))
 .collectList().block();
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
3

You can also use onStatus it allow you to filter exceptions you want

public <T> List<T> get(URI url, Class<T> responseType) {
    return  WebClient.builder().build().get().uri(url)
            .header("Authorization", "Basic " + principal)
            .retrieve()
            .onStatus(HttpStatus::is4xxClientError, this::handleErrors)
            .bodyToFlux(responseType)
            .collectList().block();
}

private Mono<Throwable> handleErrors(ClientResponse response ){
    return response.bodyToMono(String.class).flatMap(body -> {
        log.error("LOg errror");
        return Mono.error(new Exception());
    });
}
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80
  • Will it produce an exception or an empty list on 404 response at block()? –  Jul 07 '23 at 13:31
2

As of Spring WebFlux 5.3 they've added the exchange methods which allows you to easily handle different responses, like this:

public <T> List<T> get(URI url, Class<T> responseType) {
    return WebClient.builder().build().get().uri(url)
        .header("Authorization", "Basic " + principal)
        .exchangeToFlux(clientResponse -> {
            if (clientResponse.statusCode().equals(HttpStatus.NOT_FOUND)) {
                return Flux.empty();
            } else {
                return clientResponse.bodyToFlux(responseType);
            }
        })
        .collectList()
        .block();
}