簡體   English   中英

在其他函數中等待異常時如何在Kotlin協程中捕獲異常?

[英]How can I catch an exception in Kotlin coroutine when I am awaiting it in another function?

抱歉,標題含糊,無法提出更好的建議。

因此,我閱讀了這篇文章,並希望這樣做。 問題是我無法try { promise... } catch (e) { }導致錯誤被吞沒。 我可以在等待錯誤的地方捕獲錯誤,但是我不想要那樣。

我的代碼如下所示:

typealias Promise<T> = Deferred<T>

fun <T, R> Promise<T>.then(handler: (T) -> R): Promise<R> = GlobalScope.async(Dispatchers.Main) {
    // using try/catch here works but I don't want it here.
    val result = this@then.await()
    handler.invoke(result)
}

object PromiseUtil {
    fun <T> promisify(block: suspend CoroutineScope.() -> T): Promise<T> = GlobalScope.async { block.invoke(this) }
}

// somewhere in my UI testing it.
try {
    PromiseUtil.promisify { throw Exception("some exp") }
        .then { Log.d("SOME_TAG", "Unreachable code.") }
} catch (e: Exception) {
    Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}

我也閱讀了這一 本書 ,但是我想以某種方式捕獲UI代碼中的錯誤,並且不想使用runBlocking { ... }

謝謝。

永遠不會捕獲到異常,因為它不會被async調用傳播。 調用await()時會發生這種情況。

請參閱協程異常處理

您的代碼應為:

// somewhere in my UI testing it.
try {
    PromiseUtil.promisify { throw Exception("some exp") }
        .then { Log.d("SOME_TAG", "Unreachable code.") }.await() // <--- added await() call
} catch (e: Exception) {
    Log.d("ERROR_TAG", "It should catch the error here but it doesn't.")
}

但這不會編譯,因為await()是一個暫停函數。 因此,它應該更像是:

// somewhere in my UI testing it.
GlobalScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
            Log.d("ERROR_TAG", "It will catch error here")
            throwable.printStackTrace()
        }) {
   PromiseUtil.promisify { throw Exception("some exp") }
        .then { Log.d("SOME_TAG", "Unreachable code.") }.await()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM