3

I am trying to log the error response that is coming from web client using onStatus or exchange.I am able to throw exception based on error code, but unable to log response.In Success scenario I can successfully log message.

Below is my Code

I tried with both .retreive method and also .exchange method.But instead of printing response coming from client following code is printing

Response Printing currently;

 checkpoint("Body from POST *****Printing Backend Url ******[DefaultClientResponse]") 

Expected Response:

{errorCd:404, errorMsg:"Not Found",errorDetails"Person Not Found for Given Request"}

The Above Message is being returned from client, when I use postman or soapui

Using .retrieve() Method

             webClient
                .post()
                .uri(url)
                .header(ACCEPT, APPLICATION_JSON_VALUE)
                .bodyValue(request)
                .retrieve()
                .onStatus({ httpStatus -> HttpStatus.NOT_FOUND == httpStatus }, {
                    logger.info { "Client Response :${it.bodyToMono(String::class.java)}" }
                    ;Mono.error(MyCustomException))
                })
                .bodyToMono(Person::class.java)

Using .exchange() Method

 webClient
        .post()
        .uri(url)
        .header(ACCEPT, APPLICATION_JSON_VALUE)
        .body(BodyInserters.fromObject(request))
        .exchange()
        .flatMap {
                clientResponse ->
            if (clientResponse.statusCode().is4xxClientError) {
                clientResponse.body { clientHttpResponse, _ -> clientHttpResponse.body}
                logger.info { "Error Response:"+clientResponse.bodyToMono(String::class.java)}; Mono.error(MyCustomException()))
            } else clientResponse.bodyToMono(Person::class.java)
        }

AnyHelp Would be Appreciated.

Rocky4Ever
  • 828
  • 3
  • 12
  • 35
  • Does this answer your question? [Spring Webflux : Webclient : Get body on error](https://stackoverflow.com/a/49499545/1840146) – Toerktumlare Aug 24 '20 at 20:52
  • I used it also if u see my question using .exchnage() it's not logging body instead it's printing Client Response :checkpoint("Body from POST ****Client URL prinitng here ** [DefaultClientResponse]" – Rocky4Ever Aug 24 '20 at 21:00
  • i have read your question `having trouble capture client error response` which is extremly vague. Update your question with the current behaviour with proper log output in proper formatting, and then what the expected output should be so we actually can read it and see the problem. – Toerktumlare Aug 24 '20 at 23:02
  • Please see the edited question – Rocky4Ever Aug 25 '20 at 00:08

0 Answers0