首页 > 解决方案 > 使用协程时无法捕获网络错误,但可以在 RxJava 2 中捕获该错误。我错过了什么?

问题描述

我有以下代码使用协程在后台执行网络获取

    try {
        networkJob = CoroutineScope(Dispatchers.IO).launch {
            val result = fetchOnBackground(searchText)
            withContext(Dispatchers.Main) {
                showResult("Count is $result")
            }
        }
    } catch (exception: Throwable) {
        showResult(exception.localizedMessage)
    }

当网络在那里时,一切都很好。但是,当主机不正确或没有网络时,它就会崩溃。catch抓不住了

当我使用 RxJava 编码时

    disposable = Single.just(searchText)
        .map{fetchOnBackground(it)}
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            { showResult("Count is $it") },
            { showResult(it.localizedMessage) })

一切正常。即使在没有网络的情况下,错误也会在错误回调中被捕获。

我在协程代码中错过了什么,在使用协程时我无法捕捉到错误?

注意:网络抓取使用的是 OkHttp。

标签: androidkotlinrx-java2okhttp3kotlin-coroutines

解决方案


好像我需要try-catchCouroutineScope(Dispatchers.IO).launch

    networkJob = CoroutineScope(Dispatchers.IO).launch {
        try {
            val result = fetchOnBackground(searchText)
            showResult("Count is $result")
        } catch (exception: Throwable) {
            showResult(exception.localizedMessage)
        }
    }

我将 my 更改showResult为暂停功能,以便它可以包含withContext(Dispatchers.Main)

private suspend fun showResult(result: String) {
    withContext(Dispatchers.Main) {
        // Code that show the result
    }
}

推荐阅读