【问题标题】:Throw error if firebase document doesn't exist如果 firebase 文档不存在则抛出错误
【发布时间】:2021-12-02 10:34:52
【问题描述】:

有人可以帮我弄清楚我做错了什么吗?我想在继续我的函数之前先检查一个文档是否存在,如果它不存在,我会抛出一个错误。但是这个错误永远不会被抓住?这是我要抛出错误的函数:

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 new Error("customer didn't exist");
    }
  }
}

以及我如何调用函数:

StoreGateway.addCustomerToStore(
  req.params.customerId
)
  .then(() => {
    res
      .status(200)
      .json("Success");
  })
  .catch((err) => {
    res.status(500).json(err);
  });
}

现在如果文档不存在,控制台会打印“客户不存在”,但我从未得到状态 500。

【问题讨论】:

    标签: typescript firebase google-cloud-firestore promise


    【解决方案1】:

    问题是你只是返回一个错误而不是拒绝承诺。你可以按照以下两种方法来拒绝一个 Promise。

    1。抛出新的错误
    if (customer.exists) {
        //do other stuff
    } else {
        console.log("customer didn't exist")
        throw new Error("customer didn't exist");
    }
    

    2。返回一个被拒绝的承诺

    if (customer.exists) {
        //do other stuff
    } else {
        console.log("customer didn't exist")
        return Promise.reject(new Error("customer didn't exist"));
    }
    

    【讨论】:

    • 谢谢!我因为没有看到错误消息而被甩了,但我必须这样做res.status(500).json(err.message);
    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2016-07-12
    • 1970-01-01
    相关资源
    最近更新 更多