我一直在用协程找出错误处理方面的问题,我已经按照以下步骤缩小了单元测试的范围:
一切都很好。但是,当我尝试使用相同的协程范围来启动新的协程时,通常会例外地完成,但有相同的例外。
这是测试:
fun `when you throw an exception in a coroutine scope, is the coroutine scope dead?`() {
val parentJob = Job()
val coroutineScope = CoroutineScope(parentJob + Dispatchers.Default)
val deferredResult = coroutineScope.async { throw IllegalStateException() }
runBlocking {
try {
deferredResult.await()
} catch (e: IllegalStateException) {
println("We caught the exception. Good.")
}
try {
coroutineScope.async { println("we can still use the scope") }.await()
} catch (e: IllegalStateException) {
println("Why is this same exception still being thrown?")
}
}
}
这是测试的输出:
We caught the exception. Good.
Why is this same exception still being thrown?
为什么会这样呢?
我应该如何处理例外情况?
Either<Result, Exception>
吗?注意我正在使用Kotlin 1.3
当您在范围中启动协程时(使用async
或launch
),默认情况下协程失败会取消该范围以立即取消所有其他子级。这种设计避免了晃动和丢失异常。
这里的一般建议是:
除非确实需要并发,否则不要使用async
/ await
。当使用暂停函数设计代码时,不需要太多使用async
和await
。
如果确实需要并发执行,请遵循以下模式:
coroutineScope {
val d1 = async { doOne() }
val d2 = async { doTwo() }
...
// retrieve and process results
process(d1.await(), d2.await(), .... )
}
如果你需要处理的并发操作的失败,然后把try { ... } catch { ... }
周围coroutineScope { ... }
搭上故障在任何并发执行的操作。
SupervisorJob
),可以进行细粒度的异常处理。您可以在文档https://kotlinlang.org/docs/reference/coroutines/exception-handling.html中阅读更多内容。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句