【问题标题】:Returning an error changes method signature返回错误更改方法签名
【发布时间】:2022-01-23 23:49:06
【问题描述】:

我从教程中了解到,返回一个可抛出的,不应该改变方法返回类型。

这是我的尝试:

  1. 使用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>
}
  1. 当使用mapFlux.error时(我也试过Mono.error),当我在map中引入Flux.error时,函数返回类型更改为Flux&lt;Object&gt;
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


【解决方案1】:

你应该在handle之前移动timeout

 return httpClient.exchange(req, TokenResponse.class)
        .timeout(Duration.ofSeconds(10))
        .handle((response, sink) -> {

至于map的情况,看一下方法签名:

Flux map(Function<? super T,? extends V> mapper)

map 接受Function&lt;T, U&gt; 并返回Flux&lt;U&gt;,返回Flux.error 无效。您可以简单地在 map 中使用 throw,Reactor 会将其转换为正确的错误信号我认为 handle 更适合这种情况。

有用的链接:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2016-09-06
    相关资源
    最近更新 更多