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

标签 android firebase kotlin kotlin-coroutines

我正在使用新的 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/

相关文章:

Android报错: java. lang.Object无法解析,缺少Android 4.2.2 "directory"

android - 如何减少android中的图像像素?

android - 如何从 Android 应用程序调用 C/C++ 二进制文件(在 linux 服务器上移植)

firebase - 我想在我的Flutter应用程序中从Firebase数据库中获取当前用户数据

kotlin - 如何在 Kotlin 中获取对象的地址?

java - Android:我的加密/解密不起作用,我得到奇怪的输出

firebase - 为什么我无法更改 Firebase 引用的优先级(权限被拒绝)

ios - 自动完成文本字段和 Firebase

android - 在构建版本中找不到数据类 Kotlin 的序列化程序

java - proguard 规则不适用于某些 Java 文件