Spring Webflux : Webclient : Get body on error

后端 未结 8 2241
失恋的感觉
失恋的感觉 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:47

    I had just faced the similar situation and I found out webClient does not throw any exception even it is getting 4xx/5xx responses. In my case, I use webclient to first make a call to get the response and if it is returning 2xx response then I extract the data from the response and use it for making the second call. If the first call is getting non-2xx response then throw an exception. Because it is not throwing exception so when the first call failed and the second is still be carried on. So what I did is

    return webClient.post().uri("URI")
        .header(HttpHeaders.CONTENT_TYPE, "XXXX")
        .header(HttpHeaders.ACCEPT, "XXXX")
        .header(HttpHeaders.AUTHORIZATION, "XXXX")
        .body(BodyInserters.fromObject(BODY))
        .exchange()
        .doOnSuccess(response -> {
            HttpStatus statusCode = response.statusCode();
            if (statusCode.is4xxClientError()) {
                throw new Exception(statusCode.toString());
            }
            if (statusCode.is5xxServerError()) {
                throw new Exception(statusCode.toString());
            }
        )
        .flatMap(response -> response.bodyToMono(ANY.class))
        .map(response -> response.getSomething())
        .flatMap(something -> callsSecondEndpoint(something));
    }
    

提交回复
热议问题