java - 将 exchange() 与 Spring WebClient 一起使用时如何抛出 WebClientResponseException

标签 java spring spring-webclient

当将 Spring WebClient 的 retrieve() 方法与 bodyToMono 结合使用时,将应用默认错误处理(如果响应具有状态代码 4xx 或 5xx,则 Mono 将包含 WebClientException)。在错误情况下,生成的 WebClientException 非常有用,因为它包含请求和响应,这非常方便,例如用于记录。此外,我可以很好地就地对错误使用react。

/*
 * Easy to use retrieve() with default error handling:
 * By default, if the response has status code 4xx or 5xx, the Mono will contain a WebClientException - AWESOME!
 */
public Optional<MyType> getMyType() {
    try {
        MyType result = client
                .get()
                .uri("/myType")
                .retrieve().bodyToMono(MyType.class).block();

        return Optional.ofNullable(result);
    } catch (NotFound e) {
        return Optional.empty();
    }
}

但是,有时我需要知道响应的确切状态代码,以便在进一步处理此响应时对其使用react。同时获取状态代码的唯一方法是调用 exchange() 方法而不是 retrieve() 方法。不幸的是,在那种情况下,默认的错误处理不会被应用。原因似乎是在 ClientResponse 上调用 bodyToMono() 与在 ResponseSpec 上调用它具有不同的语义。

我无法从 Spring 调用已经实现的方法来“触发”错误处理,因为所有好的方法都作为私有(private)方法隐藏在 WebClient 中。

即使我尝试“手动”创建 WebClientResponseException 我也做不到 访问请求以提供给异常。

public String updateMyType() {
    ClientResponse response = client
            .put()
            .uri("/myType")
            .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
            .body(fromObject(new MyType()))
            .exchange()
            .block();

    if (response.statusCode().equals(HttpStatus.CREATED)) {
        return "OK";
    } else if (response.statusCode().equals(HttpStatus.NO_CONTENT)) {
        return "updated";
    } else {
        byte[] bodyBytes = null; // already implemented by Sping but not accessible
        Charset charset = null; // already implemented by Sping but not accessible
        HttpRequest request = null; // where should I get this from?
        throw WebClientResponseException.create(response.statusCode().value(),
                response.statusCode().getReasonPhrase(),
                response.headers().asHttpHeaders(),
                bodyBytes,
                charset,
                request);
    }
}

“模仿”与 retrieve() 方法相同行为的最佳方式是什么?

最佳答案

回答问题时可能不是这种情况,但自 Spring 5.2 以来,ClientResponse有一个 createException()将构建并返回 Mono<WebClientResponseException> 的方法.

clientResponse.createException()
              .flatMap(e -> handleException(e))

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/ClientResponse.html#createException--

https://github.com/spring-projects/spring-framework/commit/b4207823afa0f48e06d6bbfe9ae8821e389e380f

关于java - 将 exchange() 与 Spring WebClient 一起使用时如何抛出 WebClientResponseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55921619/

相关文章:

java - 我的@Cacheable 似乎被忽略了( Spring )

java - Spring XML+属性配置到Java类

java - 如何并行调用多个http请求(具有重试功能)并等待所有请求完成?

java - 如何使用 Spring WebClient 反序列化通用响应

Java AES加密: need files to decrypt properly in freely available decryptor tools

java - 绝对 uri : http://www. springsource.org/tags/form 无法在 web.xml 或随此应用程序部署的 jar 文件中解析

java - Spring请求范围bean

Java泛型和 "Bound mismatch"

java - JDBC 中的 Oracle 到 Postgresql 迁移问题