3

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.

pixel
  • 24,905
  • 36
  • 149
  • 251

1 Answers1

3

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
                                })
                )
Michael McFadyen
  • 2,675
  • 11
  • 25