Search code examples
spring-bootspring-webfluxspring-webclient

How to handle 404 in webclient retrive


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?


Solution

  • 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();