如何解决优雅地处理异步函数中的错误
基于上一个问题gracefully handling errors from suspend functions,此问题基于处理异步函数中的错误。
以下是片段中的代码。
var userAsync: Deferred<User?>? = null
arguments?.getLong("id")?.let {
// findById may throw an error
userAsync = async { userModel?.findById(it) }
}
val data = userAsync?.await() // Main thread,update UI
findById
如下一节课
class UserModel {
suspend fun findById(id : Int) : User? {
throw Exception("just like that") // crashes
}
}
尝试
在await
之前添加,它捕获了错误,但仍在运行时崩溃。
userAsync.invokeOnCompletion { cause: Throwable? ->
if (cause != null) {
println("Error: " + cause.localizedMessage)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。