【问题标题】:Is it possible to re-throw an error in the calling method in RxAndroid?是否可以在 RxAndroid 中的调用方法中重新抛出错误?
【发布时间】:2020-09-30 17:20:45
【问题描述】:

.Net TPL 的启发,我试图找到一种方法来处理RX 管道之外的错误。具体来说,如果出现错误,我希望 Observer 管道停止,并将控制权传回给周围的方法。比如:

public void testRxJava() {
    try {
        Observable.range(0, 5)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .map(i -> { throw new RuntimeException(); })
            .subscribe();
    } catch (Exception ex) {
        // I was hoping to get here on the main thread, but crashed instead
        Log.i("Test", "Will never get here");
    }
}

这将导致应用程序因io.reactivex.rxjava3.exceptions.OnErrorNotImplementedException 而崩溃,这不会在catch 子句中捕获,而是会调用主线程的uncaughtException() 处理程序。

尝试从subscribe() 中的错误处理程序抛出也不起作用,再次退回到uncaughtException() 处理程序。

有没有办法重新抛出或以其他方式将错误信息传递给调用方法?

here 发现了一个与 C# 类似的问题。

【问题讨论】:

  • 您可以在onResumeNext 中捕获错误并根据该Exception 的实例调用您希望的方法。由于错误本身也将在subscribeonError 回调中结束,您可以将其设置为不执行任何操作,或者直接忽略那里的那种错误。

标签: java android rx-android reactivex


【解决方案1】:

您是否尝试过像这样捕获错误

    Observable.range(0, 5)
        .subscribeOn(Schedulers.newThread())
        .doOnError {
            //your error caught here
        }         
        .observeOn(AndroidSchedulers.mainThread())
        .map({ i -> throw RuntimeException() })
        .subscribe()

【讨论】:

  • 它与从subscribe()投掷的效果相同,这不是我想要的。我正在寻找一种将控制权传递给周围方法的方法。
【解决方案2】:

这就是我最终要做的。据我所知,这是唯一离开 ReactiveX 管道,让周围的代码处理错误的方法。如果有人有更优雅的方式会很高兴:

public void testRxJava() {
    try {
        // will be null if no error, will hold a Throwable on error
        AtomicReference<Throwable> opError = new AtomicReference<>(null);

        Observable.range(0, 5)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .map(i -> { throw new RuntimeException(); }) // throws
            .blockingSubscribe(
                result -> Log.i(TAG, "will never happen"),
                error -> { opError.set(error); } // sets reference to the error without crashing the app
            );

        // re-throw
        if(opError.get() != null) {
            throw new Exception(opError.get());
        }

    } catch (Exception ex) {
        Log.e("Test", "exception", ex);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多