【发布时间】:2020-01-20 11:50:23
【问题描述】:
我有 3 个微服务应用程序。我正在尝试使用响应包中的 webclient 进行 2 获取异步调用,然后在收到响应时将它们组合起来。
Mono<Person> personMono = client.get().uri("/person/{id}", personId)
.retrieve().bodyToMono(Person.class);
Mono<List<Hobby>> hobbiesMono = client.get().uri("/person/{id}/hobbies", personId)
.retrieve().bodyToFlux(Hobby.class).collectList();
Map<String, Object> data = Mono.zip(personMono, hobbiesMono, (person, hobbies) -> {
Map<String, String> map = new LinkedHashMap<>();
map.put("person", personName);
map.put("hobbies", hobbies);
return map;
})
.block();
我的问题是如何在 get 调用中添加异常处理?
如何检查我得到的是 404 还是 204 或其他?
我试过了:
- 将 .onStatus() 添加到 GET 调用中
.onStatus(HttpStatus::is4xxClientError, clientResponse ->
Mono.error(new Data4xxException(String.format(
"Could not GET data with id: %s from another app, due to error:
%s", key, clientResponse))))
.onStatus(HttpStatus::is5xxServerError, clientResponse ->
Mono.error(new Data5xxException(
String.format("For Data %s, Error Occurred: %s", key, clientResponse))))
- 添加异常处理程序 - 但我完全没有控制器,所以这似乎不起作用。
@ExceptionHandler(WebClientException.class)
public Exception handlerWebClientException(WebClientException webClientException) {
return new Data4xxException("Testing", webClientException);
}
- 添加了一个包含 ControllerAdvice 和 ExceptionHandler 的类
@ControllerAdvice
public class WebFluxExceptionHandler {
@ExceptionHandler(WebClientException.class)
public Exception handlerWebClientException(WebClientException webClientException) {
return new Data4xxException("Testing", webClientException);
}
}
但我没有看到它们打印在 spring-boot 日志中。
Mono.zip.block() 方法只是返回 null,实际上并没有抛出任何异常。
如何让zip方法抛出异常而不返回null?
【问题讨论】:
-
什么是 Data4xxException?它是自定义异常吗?你说你没有控制器那么你如何调用你的代码?
-
是的,抱歉忘了提,这是一个自定义异常。我的代码是一个 springboot 应用程序,它使用来自 JMS 的数据,所以我有监听器。
标签: java spring-boot spring-webflux