Spring Webflux : Webclient : Get body on error

后端 未结 8 2189
失恋的感觉
失恋的感觉 2021-02-05 09:04

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

WebClient.create()
            .post()
            .uri(url)
            .syncBody(body)
            .a         


        
8条回答
  •  有刺的猬
    2021-02-05 09:23

    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().

提交回复
热议问题