Spring-Webflux : Print Error Response and throw exception incase of error from web client

Viewed 828

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.

0 Answers
Related