Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize error response without object mapper in WebClient onErrorResume

I wonder if there is a better way to get error response in WebClient in a way that does not involve using additional ObjectMapper when calling onErrorResume?

In my WebClient:

import org.springframework.web.reactive.function.client.WebClientResponseException.BadRequest

// ...

.onErrorResume(BadRequest::class.java, badRequestToMyDto())
    private fun badRequestToMyDto(): (BadRequest) -> Mono<out MyDto> =
        { it: BadRequest ->
            val error = objectMapper.readValue<ErrorResponseDto>(it.responseBodyAsByteArray)
            // ...
}

There is a method .bodyToMono so I wonder if there is something similar that can be used in onErrorResume.

like image 707
pixel Avatar asked Jul 31 '26 12:07

pixel


1 Answers

You can use retrieve() in combination with onStatus to get access the client response when it is an "error". You can then invoke bodyToMono on it to unmarshall the response to a java object. Depending on the content type of the response body, spring will use the correct decoder. For examaple, if the body is json, it will use an ObjectMapper for unmarshalling.

WebClient.builder().build()
                .get()
                .uri("localhost:8080")
                .retrieve()
                .onStatus(HttpStatus::isError, clientResponse ->
                        clientResponse.bodyToMono(MyErrorResponse.class)
                                .flatMap(body -> {
                                    // logic
                                })
                )
like image 120
Michael McFadyen Avatar answered Aug 03 '26 05:08

Michael McFadyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!