Home > Software engineering >  How i return Empty mono if the request doesn't return error using webClient
How i return Empty mono if the request doesn't return error using webClient

Time:11-12

i want to know how return a empty Mono when i use webClient, i have this code and it works when the request return a user.

public User getUserByUsername(String username) {
            Mono<User> user = webClient.get().uri(uriBuilder -> uriBuilder
                    .path("localhost:8090/user"   "/getByUsername").queryParam("username", username).build())
                    .retrieve()
                    .bodyToMono(User.class);

            User userRet = user.block();
            return userRet;
        
    }

CodePudding user response:

First of all, don't use block() if you really want to take full advantage of using reactive stack. With it you are blocking the thread to wait for a response, don't do that. You must always handle Mono and Flux in your code instead. Something along the following lines:

public Mono<User> getUserByUsername(String username) {
    return webClient.get().uri(uriBuilder -> uriBuilder
            .path("localhost:8090/user"   "/getByUsername").queryParam("username", username).build())
            .retrieve()
            .bodyToMono(User.class);
}

You can then specify what you want to do if the response is 4XX or 5XX. Below the example for 5XX:

public Mono<User> getUserByUsername(String username) {
    return webClient.get().uri(uriBuilder -> uriBuilder
            .path("localhost:8090/user"   "/getByUsername").queryParam("username", username).build())
            .retrieve()
            .onStatus(HttpStatus::is5xxServerError, response -> Mono.empty())
            .bodyToMono(User.class);
}
  • Related