2 years ago

#67618

test-img

ging

Asynchronous call using Spring webclient and just log the error without aborting the flow

I am trying to make an asynchronous call to a rest service using Spring webclient. I dont care if there is any exception during this call, but i want to just log if its successfull or failure (With http Status and details if Failure of course) but i want to continue to flow without stopping the flow. Can anyone suggest how can i improve below code:

In general , with regular try catch block I can do below:

try {
   restTemplate.execute(....);
} catch(HttpStatusCodeException e) {
        //log and continue the flow....
}

What I came up is with below, but not sure if its the best way to execute a webclient as i am still trying to understand all the intermittent or terminal operations within it.

@Async
public void test() {
   webclient
   .post().uri("/urihere")
   .bodytoMono(requestBody)
//as exchange is deprecated
   .exchangeToMono(response -> {
       if(response.statusCode().is4xxHttpClientError) || response.statusCode().is5xxHttpServerError)) {
           //log with response body
       } else {
           //log successs response.
       }
   });
}

I understand that I don't need to do a .block() as I don't want to wait until the request is completed. But what I am trying to understand is the test method with web client call have the same functionality as in with try catch ? Meaning, we just make a call and log the request /response but don't worry about the response?

Or am I doing anything incorrectly here. Need suggestions on above code for improvements or standards please (Is it fully reactive in nature with above code for the requirement is what I am trying to understand).

spring-boot

reactive-programming

spring-webflux

webclient

reactive

0 Answers

Your Answer

Accepted video resources