如何 return 使用 .await() 调用的方法的异常

How to return an exception from a method called with .await()

我正在使用新的 google 服务协程扩展函数实现 return 异步调用异常

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)
}

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

现在我的问题是。

我怎么知道或return这两种方法抛出一个异常?

既然是Task,异常应该return同一个对象的形式,我已经阅读了.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 中的 suspend fun 产生错误,您的 catch 将被触发。

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