如何解决Kotlin协程-从暂停函数优雅地处理错误
尝试使用从异步方法调用的暂停函数实现对错误的优雅处理,如何捕获由暂停方法引发的错误。
suspend fun findById(id: Long): User? {
throw Exception("my exception") // intentionally throwing to simulate error situation.
return userModel.findById(id) // IO,may throw an error
}
调用方,通过IO线程启动
GlobalScope.launch(Dispatchers.IO) {
try {
var userAsync: Deferred<User?>? = null
arguments?.getLong("id")?.let {
userAsync = async { viewModel?.findById(it) } // async for efficiency as i've other async methods too.
}
val data = userAsync?.await()
withContext(Dispatchers.Main) {
user = data // data binding,populating UI fields of user
}
} catch (exception: Exception) {
withContext(Dispatchers.Main) { fault(exception) }
}
}
故障方法
private fun fault(exception: Exception) {
Log.d("User","fault: ${exception.localizedMessage}") // expecting output
}
当前运行时崩溃,想要实现错误的优雅处理。
尝试2
试图将尝试捕获放置在异步块中,但它不喜欢它。
var userAsync: Deferred<UserVO?>? = null
arguments?.getLong("id")?.let {
userAsync = async {
try {
delegate?.findById(it)
} catch (e: Exception) {
print(e)
}
}
}
解决方法
我会使用[{'name': 'impressions','values': [{'value': 0,'end_time': '2020-09-11T07:00:00+0000'},{'value': 4,'end_time': '2020-09-12T07:00:00+0000'}]},{'name': 'reach',{'value': 1,'end_time': '2020-09-12T07:00:00+0000'},'end_time': '2020-09-13T07:00:00+0000'},{'value': 2,'end_time': '2020-09-14T07:00:00+0000'}]}]
使您的协程正常失败:
1)定义处理程序:
CoroutineExceptionHandler
2)重构您的findById函数以在IO上下文中执行,并使您的ui代码成为主要安全对象:
val exceptionHandler = CoroutineExceptionHandler { context,error ->
// Do what you want with the error
Log.d(TAG,error)
}
- 在
suspend fun findById(id : Int) : User? = withContext(Dispatchers.IO){ when(id){ 0 -> throw Exception("not valid") else -> return@withContext User(id) } }
中启动您的工作(并更新ui),并传递exceptionHandler来启动协程生成器以捕获异常:
MainScope
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。