Spring Webflux : Webclient : Get body on error

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

    Note that as of writing this, 5xx errors no longer result in an exception from the underlying Netty layer. See https://github.com/spring-projects/spring-framework/commit/b0ab84657b712aac59951420f4e9d696c3d84ba2

    0 讨论(0)
  • 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));
    }
    
    0 讨论(0)
提交回复
热议问题