[英]Handle exceptions in coroutine launch?
For example, how do we handle exceptions in myHttpTask
and myCpuTask
?例如,我们如何处理
myHttpTask
和myCpuTask
中的异常? and make sure we call result.error(exception)
in the main thread?并确保我们在主线程中调用
result.error(exception)
?
// The scope for the UI thread
private val mainScope = CoroutineScope(Dispatchers.Main)
override fun onMethodCall(call: MethodCall, result: Result) {
mainScope.launch {
Log.e(TAG, "onMethodCall: I'm working in thread ${Thread.currentThread().name}")
when (call.method) {
"hello" -> {
withContext(Dispatchers.IO) {
// Run code on a IO thread (the amount of IO threads are 64 by default).
myHttpTask()
}
withContext(Dispatchers.Default) {
// Run code on a CPU thread (the amount equals the amount of CPU cores).
myCpuTask()
}
// This will run on the main thread
result.success("world")
}
else -> result.notImplemented()
}
}
}
Because coroutines allow to write a regular, sequential code for asynchronous operations, we can use the same techniques as for any other sequential code - try... catch
.因为协程允许为异步操作编写常规的顺序代码,所以我们可以使用与任何其他顺序代码相同的技术 -
try... catch
。 This is true as long as we only invoke suspend functions and we don't launch anything in the background using launch()
, async()
, etc.只要我们只调用挂起函数并且不使用
launch()
、 async()
等在后台启动任何东西,情况就是如此。
For example in your case it could work like this:例如,在您的情况下,它可以像这样工作:
override fun onMethodCall(call: MethodCall, result: Result) {
mainScope.launch {
Log.e(TAG, "onMethodCall: I'm working in thread ${Thread.currentThread().name}")
when (call.method) {
"hello" -> try {
withContext(Dispatchers.IO) {
// Run code on a IO thread (the amount of IO threads are 64 by default).
myHttpTask()
}
withContext(Dispatchers.Default) {
// Run code on a CPU thread (the amount equals the amount of CPU cores).
myCpuTask()
}
// This will run on the main thread
result.success("world")
} catch (e: Throwable) {
// Just an example, I don't know if such a method exists.
result.failure("Error: $e")
}
else -> result.notImplemented()
}
}
}
While handling the exception, it will properly jump back to the main thread, as we would expect.在处理异常时,它会像我们预期的那样正确地跳回主线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.