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

Firebase文档不存在时抛出的错误无法被catch捕获问题求助

问题排查结果

核心原因

async函数返回普通值(包括Error实例)时,会被包装为*成功状态(fulfilled)的Promise,只有主动throw抛出错误、或函数内部出现运行时异常,才会返回失败状态(rejected)*的Promise,进而被catch回调捕获。你当前代码中使用return new Error(...)返回错误,错误对象会作为成功返回值传入then回调,自然不会触发500状态码返回。

修复方案

修改addCustomerToStore方法内的错误抛出逻辑,将return改为throw即可:

class StoreGateway {
  async addCustomerToStore(
    customerId: string
  ) {
    const customer = await fb.customersCollection.doc(customerId).get();
    if (customer.exists) {
      //do other stuff
    } else {
      console.log("customer didn't exist")
      // 替换return为throw,触发Promise rejected状态
      throw new Error("customer didn't exist");
    }
  }
}

修改后原有调用逻辑无需调整,文档不存在的场景会自动进入catch分支返回500状态码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:30:03