无法处理 firebase 函数中的异常
我试图理解为什么这个 throwable 没有在我的 catch 块中被捕获,但没有成功:
CoroutineScope(IO).launch {
try { FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (task.isSuccessful) {
token = task.result
}
throw Exception("Hi There!")
}).await()
getUsers().await()
}catch (e: Exception){
binding.txtTitle.text = "Error: ${e.message}"
}
}
异常被调用,但应用程序崩溃并且不被 catch 块处理。但是,如果我在 addOnCompleteListener 之外抛出异常,则异常会正常处理。我的目标是在没有可用令牌的情况下停止执行 getUsers 函数。
i'm trying to understand with no luck why this throwable is not catched in my catch block:
CoroutineScope(IO).launch {
try { FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (task.isSuccessful) {
token = task.result
}
throw Exception("Hi There!")
}).await()
getUsers().await()
}catch (e: Exception){
binding.txtTitle.text = "Error: ${e.message}"
}
}
The exception is called but the app crash and not handle by the catch block. But if i throw an exception outside the addOnCompleteListener the exception is handled normally. My objective is to stop the execution of the getUsers function if no token is available.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
OnCompleteListener
中引发的异常不会传播到外部作用域,它的作用域是OnCompleteListener
块。为了实现您的目标,我建议将代码重写为如下所示:await
函数等待任务完成。The exception which is thrown in
OnCompleteListener
will not propagate to the outer scope, it is scoped toOnCompleteListener
block. To achieve your objective I would recommend to rewrite the code to something like the following:await
function waits for task to complete.