Dheeraj Raisinghani
Dheeraj Raisinghani

Reputation: 37

Spring webflux 5.2.3 bodyToMono called after empty Mono in onStatus

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 ?

Upvotes: 0

Views: 3477

Answers (2)

Martin Tarjányi
Martin Tarjányi

Reputation: 9937

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

Upvotes: 4

Toerktumlare
Toerktumlare

Reputation: 14712

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

Upvotes: 0

Related Questions