gpt4 book ai didi

android - 如何从使用 .await() 调用的方法返回异常

转载 作者:行者123 更新时间:2023-12-02 12:46:23 25 4
gpt4 key购买 nike

我正在使用新的 google services coroutines 扩展函数来实现从异步调用中返回异常

suspend fun saveUserToken(user: User): Resource<Boolean> {
val result = FirebaseInstanceId.getInstance().instanceId.await()
user.deviceToken = result.token
FirebaseFirestore.getInstance().collection("user").document(user.uid).set(user).await()
return Resource.success(true)
}

这里我做了两个异步操作,第一个检索用户设备 token ,第二个将该设备 token +用户数据存储到 Firestore

现在我的问题是。

如果其中一个是 throw ,我如何知道或从这两种方法返回异常?

由于是一个任务,异常应该以相同对象的形式返回,我已经阅读了 .await() 方法以了解它如何处理异常
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
result
}
} else {
throw e
}
}

return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
if (isCanceled) cont.cancel() else cont.resume(result)
} else {
cont.resumeWithException(e)
}
}
}
}

这里有两种类型的异常,一种是调用它的任务异常(这是我想在我的第一个代码块中捕获的异常),第二种是取消协程时触发的 CancellationException

最佳答案

只需像使用任何其他代码一样使用 try/catch:

try {
val result = FirebaseInstanceId.getInstance().instanceId.await()
user.deviceToken = result.token
FirebaseFirestore.getInstance().collection("user").document(user.uid).set(user).await()
return Resource.success(true)
}
catch (e: Exception) {
// handle the error here
}

或者您可以将 try/catch 放在对 saveUserToken 的调用周围。 .在任何一种情况下,如果 try catch 中的挂起乐趣产生错误,则您的 catch 将触发。

我建议阅读 exception handling with Kotlin coroutines 上的文档.

关于android - 如何从使用 .await() 调用的方法返回异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59363657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com