如何回退项目反应堆通量的错误元素onErrorReturn?

问题描述 投票:0回答:1

可以说我有一个元素抛出错误的通量。

 Flux.just("aeiou","aeio").map(x -> {
           if(!x.endsWith("u")){throws Exception;}
           return x;})
      .onErrorReturn(/*This only accepts a new element*/)
      .map(x -> x+";")
      .subscribe();

 Flux.just("aeiou","aeio").map(x -> {
           if(!x.endsWith("u")){throws Exception;}
           return x;})
      .onErrorResume(/*This doesn't do the next steps*/)
      .map(x -> x+";")
      .subscribe();

我想要这样的东西

 Flux.just("aeiou","aeio").map(x -> {
           if(!x.endsWith("u")){throws Exception;}
           return x;})
      .onErrorReturn(x -> x + "u")
      .map(x -> x+";")
      .subscribe();

文档似乎错误http://projectreactor.io/docs/core/release/reference/#_fallback_method

Flux.just("key1", "key2")
   .flatMap(k -> callExternalService(k)) 
   .onErrorResume(e -> getFromCache(k)); //k not resolved here
project-reactor reactive
1个回答
2
投票

文档是正确的。

 Flux.just("key1", "key2")
   .flatMap(k -> callExternalService(k)) 
   .onErrorResume(e -> getFromCache(k)); //k not resolved here

k没有得到解析,因为k在flatMap中声明为局部变量。它对onErrorResume()不可见。如果你在管道上方声明k,即在Flux之前,那么它将被解析。

其次,对你的另一个问题

Flux.just("aeiou","aeio").map(x -> {
       if(!x.endsWith("u")){throws Exception;}
       return x;})
  .onErrorReturn(x -> x + "u")
  .map(x -> x+";")
  .subscribe();

您必须参考API文档。 onErrorReturn()可以让你返回一个回退值。但是这个后备值有点硬编码,即你不会得到x的值。您可以简单地将值硬编码为u,但这可能无法解决您的目的。

我建议你看一下onErrorResume(Function<? super Throwable,? extends Publisher<? extends T>> fallback),因为这可以让你编写一个函数,你可以用一些逻辑来做额外的处理。

这允许您返回发布者,因此您可以执行以下操作。

.onErrorResume(e -> { //get the value of x
                       String x = <>;// you will have to write logic to get the value of x here, as it will not be available directly                          
                       return Flux.just(x+"u");
                       })
© www.soinside.com 2019 - 2024. All rights reserved.