gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:20:02 25 4
gpt4 key购买 nike

当将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com