RxJava2中的onErrorReturn只捕获了第一个错误

时间:2018-04-18 10:22:59

标签: java rx-java rx-java2

我在flowable中抛出两个异常,并使用onErrorReturn来捕获这些异常。但我发现只有第一个例外被捕获。如何捕捉所有例外?

Flowable.create(emitter -> {
    emitter.onError(new Exception("error1"));
    emitter.onError(new Exception("error2"));
    }, BackpressureStrategy.MISSING)
        .onErrorReturn(e -> {
            System.out.println("Got error " + e.getMessage());
            return "error";
        })
        .subscribe();

输出:

Got error error1
io.reactivex.exceptions.UndeliverableException: java.lang.Exception: error2
    at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:349)
    at io.reactivex.internal.operators.flowable.FlowableCreate$BaseEmitter.onError(FlowableCreate.java:271)
    at com.example.springboottest.SimpleApplication.lambda$main$0(SimpleApplication.java:48)
    at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:72)
    at io.reactivex.Flowable.subscribe(Flowable.java:13094)
    at io.reactivex.internal.operators.flowable.FlowableOnErrorReturn.subscribeActual(FlowableOnErrorReturn.java:33)
    at io.reactivex.Flowable.subscribe(Flowable.java:13094)
    at io.reactivex.Flowable.subscribe(Flowable.java:13030)
    at io.reactivex.Flowable.subscribe(Flowable.java:12890)
    at com.example.springboottest.SimpleApplication.main(SimpleApplication.java:54)
Caused by: java.lang.Exception: error2
    ... 8 more
Exception in thread "main" io.reactivex.exceptions.UndeliverableException: java.lang.Exception: error2
    at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:349)
    at io.reactivex.internal.operators.flowable.FlowableCreate$BaseEmitter.onError(FlowableCreate.java:271)
    at com.example.springboottest.SimpleApplication.lambda$main$0(SimpleApplication.java:48)
    at io.reactivex.internal.operators.flowable.FlowableCreate.subscribeActual(FlowableCreate.java:72)
    at io.reactivex.Flowable.subscribe(Flowable.java:13094)
    at io.reactivex.internal.operators.flowable.FlowableOnErrorReturn.subscribeActual(FlowableOnErrorReturn.java:33)
    at io.reactivex.Flowable.subscribe(Flowable.java:13094)
    at io.reactivex.Flowable.subscribe(Flowable.java:13030)
    at io.reactivex.Flowable.subscribe(Flowable.java:12890)
    at com.example.springboottest.SimpleApplication.main(SimpleApplication.java:54)
Caused by: java.lang.Exception: error2
    ... 8 more

1 个答案:

答案 0 :(得分:3)

val()在完成或遇到错误后结束。这是合同的一部分,没有办法解决这个问题。

你唯一可以处理多个'可观察的异常是它是否像值一样处理,而不是例外。在实践中,这最终会看起来像Scala's Either construct