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

Fab*_*ble 5 java spring spring-webclient

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

\n\n
/*\n * Easy to use retrieve() with default error handling:\n * By default, if the response has status code 4xx or 5xx, the Mono will contain a WebClientException - AWESOME!\n */\npublic Optional<MyType> getMyType() {\n    try {\n        MyType result = client\n                .get()\n                .uri("/myType")\n                .retrieve().bodyToMono(MyType.class).block();\n\n        return Optional.ofNullable(result);\n    } catch (NotFound e) {\n        return Optional.empty();\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

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

\n\n

即使我尝试“手动”创建 WebClientResponseException,我也无法访问提供异常的请求。

\n\n
public String updateMyType() {\n    ClientResponse response = client\n            .put()\n            .uri("/myType")\n            .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)\n            .body(fromObject(new MyType()))\n            .exchange()\n            .block();\n\n    if (response.statusCode().equals(HttpStatus.CREATED)) {\n        return "OK";\n    } else if (response.statusCode().equals(HttpStatus.NO_CONTENT)) {\n        return "updated";\n    } else {\n        byte[] bodyBytes = null; // already implemented by Sping but not accessible\n        Charset charset = null; // already implemented by Sping but not accessible\n        HttpRequest request = null; // where should I get this from?\n        throw WebClientResponseException.create(response.statusCode().value(),\n                response.statusCode().getReasonPhrase(),\n                response.headers().asHttpHeaders(),\n                bodyBytes,\n                charset,\n                request);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

\xe2\x80\x9cmimimic\xe2\x80\x9d 与retrieve() 方法相同行为的最佳方法是什么?

\n

ola*_*lan 4

回答问题时情况可能并非如此,但从 Spring 5.2 开始,ClientResponse有一个createException()方法可以构建并返回Mono<WebClientResponseException>.

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

Run Code Online (Sandbox Code Playgroud)

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