首页 > 解决方案 > 如何控制firebase函数中抛出错误的输出

问题描述

我在我的 firebase 函数中使用 async/await,每个调用都有可能引发错误。我不确定如何正确处理捕获每个错误。我不想将每个调用都包装在 try/catch 中,因为所涉及的代码量几乎违背了使用 await 语法的目的。

如果我让等待抛出,那么 firebase-functions 将捕获并记录它们,这很棒。但是,我不希望这些错误传播回客户端。

如何捕获所有抛出的错误并控制返回的响应?

标签: typescriptfirebaseasync-awaitgoogle-cloud-functions

解决方案


问题。巨大的尝试/捕捉:

module.exports = async (req, res) => {
  // Get the data from the request
  const input1 = req.body.input1
  const input2 = req.body.input2

  try {
    // First bit of await work
    const fileInfo = await db.getFileInfo(input2)

    // Do some non-await work
    const tempFilePath = generateUniqueTempFilePath(fileInfo)

    // More await work
    await storage.download(input1, tempFilePath)
    const checkinResult = await db.checkin(tempFilePath, data)

    const result = { checkinResult, fileInfo }
    res.json(result)
  } catch (err) {
    res.status(500).send(err.message)
  }
}

一种解决方案是将所有等待调用和相关逻辑包装在一个单独的函数中,并在端点方法中尝试/捕获一次。

例子。小 try/catch 和一个单独的函数:

const service = require('./serviceA')

module.exports = async (req, res) => {
  // Get the data from the request
  const input1 = req.body.input1
  const input2 = req.body.input2

  // Perform async code in a single call
  var result = undefined
  try {
    result = await service.perform(input1, input2)
  } catch (err) {
    res.status(500).send(err.message)
    return
  }
  res.json(result)
}

async function perform (input1, input2) {
  // First bit of await work (no try/catch!)
  const fileInfo = await db.getFileInfo(input2)

  // Do some non-await work
  const tempFilePath = generateUniqueTempFilePath(fileInfo)

  // More await work (but they should throw errors with suitable messages!)
  await storage.download(input1, tempFilePath)
  const checkinResult = await db.checkin(tempFilePath, data)

  return { checkinResult, fileInfo }
}

module.exports = { perform }

推荐阅读