You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore使用await创建文档无效且无异常,求助

问题排查与解决

先梳理核心问题点,给出对应的修复方案:

1. 确认Firestore协程依赖是否正确添加

协程版本代码失效,首先要检查是否引入了Firestore的协程扩展依赖。如果缺少该依赖,await()无法作为正确的挂起函数工作,会导致逻辑异常。

在Module级build.gradle(或build.gradle.kts)中添加以下依赖:

implementation "com.google.firebase:firebase-firestore-ktx:24.10.0" // 使用最新稳定版本
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3"

2. 修复协程代码的逻辑漏洞

你在回调里写的if (document != null)其实无效——Firestore的DocumentSnapshot永远不会为null,正确判断文档是否存在的方式是调用exists()方法。另外,原代码用currentUser!!强制非空,一旦转换失败会抛出空指针,但日志只打印异常消息,看不到完整栈轨迹,导致你误以为没捕获到异常。

修改后的协程代码:

try {
    val documentSnapshot = userCollection.document(userId).get().await()
    // 正确判断文档是否存在
    if (documentSnapshot.exists()) {
        val currentUser = documentSnapshot.toObject<User>()
        currentUser?.let { user ->
            val todo = Todo(todoId, todoName, user)
            // 等待写入操作完成
            todoCollection.document(todoId).set(todo).await()
            Log.d("todosuccess", "Todo添加成功")
        } ?: Log.d("todowarn", "User对象转换失败")
    } else {
        Log.d("todowarn", "用户文档不存在")
    }
} catch (e: Exception) {
    // 打印完整异常栈轨迹,方便定位问题
    Log.e("todoerror", "添加Todo失败", e)
}

3. 日志输出优化

原代码用Log.d("todoerror", "$e")只能打印异常消息,看不到完整调用栈,导致排查困难。换成Log.e并传入异常对象,就能输出完整的异常信息,快速定位问题。


内容的提问来源于stack exchange,提问作者Ansh T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 15:25:20