Kotlin 捕获协同路由启动调用的错误

Kotlin 捕获协同路由启动调用的错误,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,在以下代码中: private fun executeCognitoRequest(result: MethodChannel.Result, block: suspend CoroutineScope.() -> Any?) { try { CoroutineScope(Dispatchers.Default).launch { val requestResult = block() withContext(Dispatchers.Main) {

在以下代码中:

private fun executeCognitoRequest(result: MethodChannel.Result, block: suspend CoroutineScope.() -> Any?) {
  try {
    CoroutineScope(Dispatchers.Default).launch {
      val requestResult = block()
      withContext(Dispatchers.Main) {
        result.success(requestResult)
      }
    }
  } catch (exception: Exception) {
    val cognitoErrorType = CognitoErrorType.getByException(exception)
    result.error(cognitoErrorType.code, null, null)
  }
}

如果对
块的调用抛出,它会被捕获吗?

它会被捕获,但您的代码的问题是您违反了结构化并发的原则,并在
全局范围内启动了一个协程。因此,如果您从如下主函数测试代码:

fun main() {
    runBlocking {
        executeCognitoRequest(MethodChannel.Result()) {
            funThatThrows()
        }
    }
}
整个程序将在协同程序完成执行之前结束

以下是编写函数的方法:

private fun CoroutineScope.executeCognitoRequest(
        result: MethodChannel.Result,
        block: suspend CoroutineScope.() -> Any?
) {
    try {
        launch(Dispatchers.IO) {
            val requestResult = block()
            withContext(Dispatchers.Main) {
                result.success(requestResult)
            }
        }
    } catch (exception: Exception) {
        val cognitoErrorType = CognitoErrorType.getByException(exception)
        result.error(cognitoErrorType.code, null, null)
    }
}
现在,您的函数是
CoroutineScope
上的一个扩展,并且该接收器会自动调用
launch
。此外,对于阻止IO调用,您不应该使用
Default
,而应该使用
IO
调度程序

然而,我发现您的高级设计很奇怪,您从阻塞代码开始,将其转换为异步的、面向回调的代码。协同程序可以帮助您摆脱回调