如何捕获rx链的onNext阶段结果的崩溃错误?

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

[当我有下面的流程时,崩溃将在doSomethingThatWillCrash()中发生,我当时显示它会在{ error -> showError(error.message }中被捕获,但并没有发生,因为它已经在下一阶段的订阅中了

    disposable = apiRepository.fetch()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            { result -> doSomethingThatWillCrash() },
            { error -> showError(error.message }
        )

我该如何处理错误?

我可以做

try {
    disposable = apiRepository.fetch()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            { result -> doSomethingThatWillCrash() },
            { error -> showError(error.message }
        )
} catch(e:Exception) { }

    disposable = apiRepository.fetch()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            { result -> try { doSomethingThatWillCrash() } catch(e:Exception) { } },
            { error -> showError(error.message }
        )

但这很丑...有什么建议吗?

android rx-java2
2个回答
1
投票

将错误传播到onError块中如何:

disposable = apiRepository.fetch()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .doOnSuccess { doSomethingThatWillCrash() }
    .subscribe({ result ->
        // nothing to do now
    }, { error ->
        // handle all errors including one from fun `doSomethingThatWillCrash()`
        showError(error.message)
    })

不确定apiRespository.fetch()是否返回Single。如果不是,请根据您的返回类型使用适当的Rx运算符,例如.doOnNext()代表Observable等。


0
投票

一种方法是如下注册setErrorHandler

    RxJavaPlugins.setErrorHandler { error -> showError(error.message) }

    disposable = apiRepository.fetch()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            { result -> doSomethingThatWillCrash() },
            { error -> showError(error.message) }
        )

根据InterruptedException not caught on RxJava onError callback?共享

© www.soinside.com 2019 - 2024. All rights reserved.