kotlin - 在 WebClient onErrorResume 中反序列化没有对象映射器的错误响应

标签 kotlin spring-webflux project-reactor spring-webclient

我想知道是否有更好的方法在调用 onErrorResume 时不涉及使用额外的 ObjectMapper 来在 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)
            // ...
}

有一个方法 .bodyToMono 所以我想知道是否有类似的东西可以用在 onErrorResume 中。

最佳答案

您可以将 retrieve()onStatus 结合使用,以便在出现“错误”时访问客户端响应。然后,您可以对其调用 bodyToMono 以解码对 java 对象的响应。根据响应主体的内容类型,spring 将使用正确的解码器。例如,如果正文是 json,它将使用 ObjectMapper 进行解码。

WebClient.builder().build()
                .get()
                .uri("localhost:8080")
                .retrieve()
                .onStatus(HttpStatus::isError, clientResponse ->
                        clientResponse.bodyToMono(MyErrorResponse.class)
                                .flatMap(body -> {
                                    // logic
                                })
                )

关于kotlin - 在 WebClient onErrorResume 中反序列化没有对象映射器的错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70288529/

相关文章:

java - Spring webflux - 文件上传不起作用,当我从 postman 那里点击它时,它会抛出错误

kotlin - WebFlux WebTestClient 和 Kotlin 的类型干扰问题

java - Spring Security如何确保 header

spring - 如何在 Spring AMQP 中使用响应式(Reactive) RabbitListener Ack/Nack?

java - Reactor中的doAfterSucces和doOnSuccess有什么区别?

java - 没有为 feign 客户端找到类型类 kotlin.Unit 的后备实例

reflection - 在未知(任何)对象上调用kclass.memberProperties是否安全?

kotlin - Retrofit2 为什么没有Flow的CallAdapterFactory

具有通用类型的 Android 和 Moshi 适配器

oracle - R2DBC - Oracle 数据库支持