Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Webflux : Webclient : Get body on error

I am using the webclient from spring webflux, like this :

WebClient.create()             .post()             .uri(url)             .syncBody(body)             .accept(MediaType.APPLICATION_JSON)             .headers(headers)             .exchange()             .flatMap(clientResponse -> clientResponse.bodyToMono(tClass)); 

It is working well. I now want to handle the error from the webservice I am calling (Ex 500 internal error). Normally i would add an doOnError on the "stream" and isu the Throwable to test the status code,

But my issue is that I want to get the body provided by the webservice because it is providing me a message that i would like to use.

I am looking to do the flatMap whatever happen and test myself the status code to deserialize or not the body.

like image 696
adrien le roy Avatar asked Jun 16 '17 15:06

adrien le roy


People also ask

How does WebClient handle error response?

While Initialising WebClient As mentioned in the code block, whenever a 5XX/4XX Error occurs, we can throw a user defined exception, and then execute error handling logic based on those user defined exceptions. Once this error Handler is defined, we can add it in the WebClient Initialisation.

How do I get the status code from WebClient response?

GetWebResponse(request);" line. You can pull the status and response from the exception (if they exist). Yes. You still have to catch exceptions just like normal.


1 Answers

I prefer to use the methods provided by the ClientResponse to handle http errors and throw exceptions:

WebClient.create()          .post()          .uri( url )          .body( bodyObject == null ? null : BodyInserters.fromValue( bodyObject ) )          .accept( MediaType.APPLICATION_JSON )          .headers( headers )          .exchange()          .flatMap( clientResponse -> {              //Error handling              if ( clientResponse.statusCode().isError() ) { // or clientResponse.statusCode().value() >= 400                  return clientResponse.createException().flatMap( Mono::error );              }              return clientResponse.bodyToMono( clazz )          } )          //You can do your checks: doOnError (..), onErrorReturn (..) ...          ... 

In fact, it's the same logic used in the DefaultResponseSpec of DefaultWebClient to handle errors. The DefaultResponseSpec is an implementation of ResponseSpec that we would have if we made a retrieve() instead of exchange().

like image 111
Omar ZRIDI Avatar answered Sep 24 '22 06:09

Omar ZRIDI