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

基于Firestore的自定义JavaScript REST API错误捕获问题

问题根因

Firestore 的 document.get() 方法在目标文档不存在时不会抛出异常,仅会返回带有空数据的快照对象,因此原有代码不会触发错误分支,始终返回200状态码。

修改后的代码

app.get("/api/read/:id", (req, res) => {
  (async () => {
    try {
      const document = db.collection("users").doc(req.params.id);
      const productSnapshot = await document.get();
      // 判定文档是否存在
      if (!productSnapshot.exists) {
        return res.status(404).send({ message: "查询的文档ID不存在" });
      }
      const response = productSnapshot.data();
      return res.status(200).send(response);
    } catch (error) {
      console.log(error);
      return res.status(500).send({ message: "服务端运行错误", error });
    }
  })();
})

补充说明

  • productSnapshot.exists 是 Firestore 快照对象内置的布尔字段,专门用于标识对应ID的文档是否存在
  • 错误返回统一使用结构化JSON格式,方便客户端统一解析处理
  • 原有catch分支仅会捕获数据库连接异常、权限校验失败这类运行时错误,文档不存在属于业务逻辑类的正常查询结果,需要单独做判断

内容的提问来源于stack exchange,提问作者Ian Barber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:09:00