0

I've created a WebClient to make a get request, and to specifically handle the 404 error I'm using the onStatus method as shown in the snippet below.

 client.get()
                .uri(someUrl)
                .headers(someHeaders)
                .retrieve()
                .onStatus(status -> status.equals(HttpStatus.NOT_FOUND), r -> Mono.empty())
                .bodyToMono(MyJsonResponse.class)

When I get a 404 in the response, my expectation is that it should return an empty mono, however, it calls subsequent body to mono as well and tries to parse the response, which, ideally it should not do. Any suggestions ?

Martin Tarjányi
  • 8,863
  • 2
  • 31
  • 49
  • 1
    by default Mono#empty will `Create a Mono that completes without emitting any item.` meaning that it will complete and then execution will continue. So as in your case go to `bodyToMono` if you wish to just ignore, you should do something like `switchIfEmpty` and there continue pick up with what you want to do, or return an error and use `onErrorContinue` – Toerktumlare Jan 08 '21 at 13:32
  • Thanks for the clarification @Toerktumlare. It looks like something changed in the new version, it used to work as expected when the code was on Spring-webflux 5.0.x – Dheeraj Raisinghani Jan 08 '21 at 13:48

2 Answers2

3

The latest javadoc of the onStatus method recommends using onErrorResume or filter for your use case:

To ignore an error response completely, and propagate neither response nor error, use a filter, or add onErrorResume downstream, for example:

 webClient.get()
     .uri("https://example.com/account/123")
     .retrieve()
     .bodyToMono(Account.class)
     .onErrorResume(WebClientResponseException.class,
          ex -> ex.getRawStatusCode() == 404 ? Mono.empty() : Mono.error(ex));

It was indeed a behavior change in Spring not so long ago. Related discussion: https://github.com/spring-projects/spring-framework/issues/24736

Martin Tarjányi
  • 8,863
  • 2
  • 31
  • 49
0

by default Mono#empty will:

Create a Mono that completes without emitting any item.

meaning that it will complete and then execution will continue. So as in your case go to bodyToMono. if you wish to just ignore, you should do something like switchIfEmpty and there continue pick up with what you want to do, or return an Mono#error and use onErrorContinue

Toerktumlare
  • 12,548
  • 3
  • 35
  • 54