Android 当我在另一个函数中等待异常时,如何在Kotlin协程中捕获异常?

Android 当我在另一个函数中等待异常时,如何在Kotlin协程中捕获异常?,android,kotlin,kotlinx.coroutines,Android,Kotlin,Kotlinx.coroutines,很抱歉标题含糊不清,我想不出更好的了 所以我读了这篇文章,想做同样的事情。问题是我不能做尝试{promise…}catch(e){}导致错误被吞没。我可以在等待的地方抓住错误,但我不想这样 我的代码如下所示: typealias Promise<T> = Deferred<T> fun <T, R> Promise<T>.then(handler: (T) -> R): Promise<R> = GlobalScope.asyn

很抱歉标题含糊不清,我想不出更好的了

所以我读了这篇文章,想做同样的事情。问题是我不能做
尝试{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.")
}
typealias Promise=延迟
fun Promise.then(handler:(T)->R):Promise=GlobalScope.async(Dispatchers.Main){
//在这里使用try/catch很有效,但我不想在这里使用它。
val结果=this@then.await()
调用(结果)
}
对象允诺{
fun promisify(block:suspend CoroutineScope.(->T):Promise=GlobalScope.async{block.invoke(this)}
}
//在我的UI的某个地方测试它。
试一试{
PromiseUtil.promisify{throw Exception(“some exp”)}
.then{Log.d(“SOME_标记”,“无法访问的代码”)}
}捕获(e:例外){
Log.d(“ERROR_TAG”,“它应该在这里捕获错误,但它没有捕获错误”)
}
我也读了,但我想以某种方式捕捉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.")
}

该异常从未被捕获,因为它从未被
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.")
}

在您的UI上,我认为您应该使用其他扩展名
然后使用Async
,以便正确完成
wait()
。@shkschneider对此进行了测试,但没有成功,大多数情况下,在第一次之后,我没有其他异步工作要做。在您的UI上,我认为您应该使用其他扩展
thenAsync
,以便正确完成
wait()
。@shkschneider测试了这一点,但它不起作用,大多数情况下,在第一次之后,我没有其他异步工作要做。谢谢。我想在“then function”中等待它就可以了。谢谢。我想在“then function”中等待它就可以了。