Home > database >  Java Spring Webflux - WebClient .onStatus((HttpStatus::isError) to return for error handling
Java Spring Webflux - WebClient .onStatus((HttpStatus::isError) to return for error handling

Time:04-05

Small Java Spring WebClient please.

I am the client application, making calls to a server. I am not the server, neither do I control anything on the server side. The server is known to be very flaky, and there is nothing I can do on the server side.

Hence, I am building a code on the client side to handle errors. My goal is simple, when the server responds with something correct, a 200, that is good, but anything else, any error, no matter what is the error, I would like to return a default. Therefore, I went to try this:

 public static String sendPayloadToFlakyServerWithDefaultIfError() {
        final WebClient           webClient                 = WebClient.create().mutate().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE, HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).clientConnector(new ReactorClientHttpConnector(HttpClient.create().wiretap(true).protocol(HttpProtocol.H2))).build();
        final Map<String, String> payload                   = Map.of("somekeyone", "somevalueone", "somekeytwo", "somevaluetwo");
        final String response = webClient.post().uri("https://the-very-flaky-server/api/someendpoint").body(BodyInserters.fromValue(payload)).retrieve()
                .onStatus((HttpStatus::isError),
                        (it -> {
                            System.out.println("there is an error with the flaky server indeed...  "   it.statusCode().getReasonPhrase());
                            return ??? //return "something bad happened on the flaky server side";
                        })
                )
                .bodyToMono(String.class).block();
        System.out.println("the response from flaky server is "   response);
        return response;
    }

I was hoping, with .onStatus((HttpStatus::isError), I could just return, no matter what is the server error, a default value.

Unfortunately, this requires some kind of Mono of Throwable. How to achieve this please?

Maybe onStatus((HttpStatus::isError) is not the correct way to solve this?

I am a bit lost and would like to just return (not just print) the default message.

Thank you

CodePudding user response:

You can simply use onErrorReturn operator like this:

final String response = webClient.post()
        .uri("https://...")
        .body(BodyInserters.fromValue(payload))
        .retrieve()
        .bodyToMono(String.class)
        .onErrorReturn(e -> "default");
        .block();
  • Related