Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webclient returning Optional.empty() on not found response

I'm trying to make WebClient return an Optional.empty() when I get a 404, not found, from the server. But instead I get a Optional with a User object with all properties set to null.

What am I missing?

@Override
public Optional<User> getUser(Username username) {
    return webClient
            .get()
            .uri(buildUrl(username))
            .retrieve()
            .onStatus(HttpStatus.NOT_FOUND::equals, response -> Mono.empty())
            .onStatus(HttpStatus::is4xxClientError, response -> createError(response, CLIENTERROR))
            .onStatus(HttpStatus::is5xxServerError, response -> createError(response, SERVRERROR))
            .bodyToMono(User.class)
            .blockOptional();
}
like image 705
heldt Avatar asked Aug 24 '26 06:08

heldt


1 Answers

You can make use of onError* functions from Mono to handle these cases.

onErrorResume to create a empty/error Mono on exception and onErrorMap to transform exception to a different exception type.

For example:

@Override
public Optional<User> getUser(Username username) {
    return webClient
            .get()
            .uri(buildUrl(username))
            .retrieve()
            .onStatus(httpStatus -> httpStatus.is4xxClientError() && httpStatus != HttpStatus.NOT_FOUND, response -> createError(response, CLIENTERROR))
            .onStatus(HttpStatus::is5xxServerError, response -> createError(response, SERVRERROR))
            .bodyToMono(User.class)
            .onErrorResume(WebClientResponseException.NotFound.class, notFound -> Mono.empty())
            .blockOptional();
}
like image 154
A developer Avatar answered Aug 26 '26 23:08

A developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!