spring - 在微服务响应失败的情况下提取Web客户端响应,http状态码为4XX
问题描述
我对春天有点陌生。我开始使用 Web 客户端转换我的其余模板调用之一。我遇到了一些问题。我的代码如下
public Mono<TestDateResponse> getTestDate() {
WebClient.RequestBodyUriSpec requestBodyUriSpec = webClient.post();
WebClient.RequestBodySpec requestBodySpec =
requestBodyUriSpec.header(ApplicationConstants.HTTP_AUTH_TOKEN, "xyz");
requestBodyUriSpec.uri(dateLookupServiceEndPoint);
requestBodySpec.bodyValue(request);
WebClient.ResponseSpec response = requestBodySpec.retrieve().onStatus(HttpStatus::is4xxClientError, clientResponse -> {
return clientResponse.bodyToMono(ErrorResponse.class)
.flatMap(body -> {
log.info("Body is: {}", body);
return Mono.error(new ServiceException(body.getErrorMessage(), clientResponse.rawStatusCode()));
});
});
response
.toBodilessEntity()
.timeout(Duration.ofSeconds(5))
.retryWhen(
Retry.fixedDelay(maxRetryAttempts, Duration.ofMillis(fixedDelay))
.onRetryExhaustedThrow((spec, rs) -> rs.failure()));
return response.bodyToMono(TestDateResponse.class);
}
我正在尝试捕获如下响应。
try {
accountOpenDateRes = accountOpenDateMonoResponse.block(timeout);
} catch(Exception e) {
log.info("Exception in date lookup");
}
只要我的 datelookupservice 返回 TestDateResponse.class 的状态码为 200 的响应,此方法就可以正常工作。我正在寻找一种在 http 状态为 400 的情况下捕获响应的方法,其中我的响应是 ErrorResponse.class。和上面的代码导致不同的excpetion如下
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is reactor.core.Exceptions$ReactiveException: java.util.concurrent.TimeoutException: Did not observe any item or terminal signal within 5000ms in 'flatMap' (and no fallback has been configured)] with root cause
java.util.concurrent.TimeoutException: Did not observe any item or terminal signal within 5000ms in 'flatMap' (and no fallback has been configured)
at reactor.core.publisher.FluxTimeout$TimeoutMainSubscriber.handleTimeout(FluxTimeout.java:294)
似乎我无法弄清楚 onStatus 的用法。有什么建议么?。谢谢
解决方案
推荐阅读
- xslt-1.0 - Copy-of 将根和所有子项复制到 xml 数据库列
- node.js - 通过 Socket.io 发送文件数据
- r - 如何计算组之间的重叠时间间隔
- sqlite - 无法使用节点 14.16.1 运行 sqlite 查询
- c# - 天蓝色发布管道没有为定义的环境构建应用程序设置
- reactjs - ReactJS:输入 onChange 不更新状态
- mysql - 端口 3349 上的 Windows Identity Foundation 和端口转发
- python - 如何在 python 的风筝副驾驶中禁用数字完成?
- html - 图像不尊重 div 的大小
- java - 消费者无法处理消息 - Spring Cloud Stream