【发布时间】:2022-01-23 23:49:06
【问题描述】:
我从教程中了解到,返回一个可抛出的,不应该改变方法返回类型。
这是我的尝试:
- 使用
handle时,一切都很好,直到我添加.timeout(),然后函数返回类型更改为Flux<Object>
private Flux<String> exampleHandle()
{
MutableHttpRequest<String> req = HttpRequest.GET("http://localhost:8080");
return httpClient.exchange(req, TokenResponse.class)
.handle((response, sink) -> {
Optional<TokenResponse> optionalBody = response.getBody();
if (optionalBody.isEmpty()) {
sink.error(new InitializationException("Failed to fetch authentication token. Body is null."));
} else {
TokenResponse tokenResponse = optionalBody.get();
String accessToken = tokenResponse.getAccessToken();
if (accessToken != null) {
sink.next(accessToken);
} else {
sink.error(new InitializationException("Failed to fetch authentication token. Authentication token is null."));
}
}
});
// .timeout(Duration.ofSeconds(10)); // Timeout changes return type to Flux<Object>
}
- 当使用
map和Flux.error时(我也试过Mono.error),当我在map中引入Flux.error时,函数返回类型更改为Flux<Object>
private Flux<String> exampleMap()
{
MutableHttpRequest<String> req = HttpRequest.GET("http://localhost:8080");
return httpClient.exchange(req, TokenResponse.class)
.map(response -> {
Optional<TokenResponse> optionalBody = response.getBody();
if (optionalBody.isEmpty()) {
return Flux.error(new InitializationException("Failed to fetch authentication token. Body is null."));
} else {
TokenResponse tokenResponse = optionalBody.get();
String accessToken = tokenResponse.getAccessToken();
if (accessToken != null) {
return accessToken;
} else {
return Flux.error(new InitializationException("Failed to fetch authentication token. Authentication token is null."));
}
}
});
}
谁能解释我做错了什么?谢谢!
【问题讨论】:
-
如果你的 Flux 超时,那么它就不能返回一个字符串,我猜这就是它变成 Object 的原因。映射时,不应返回容器类型(这就是 flatMap 的用途)
-
您是否将抛出
Exception与返回混淆?他们不是一回事。当您从方法返回某些内容时,控制权将传递给调用您的方法。当你扔东西时,控制权被传递给catch子句,这可能是堆栈的几个步骤。
标签: java reactive-programming project-reactor reactor