【问题标题】:How to control the output of thrown errors in firebase functions如何控制firebase函数中抛出错误的输出
【发布时间】:2020-02-18 03:14:36
【问题描述】:

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

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

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

【问题讨论】:

    标签: typescript firebase async-await google-cloud-functions


    【解决方案1】:

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

    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 }
    

    【讨论】:

    • 这是我目前对解决方案的理解。我同意我应该将我的逻辑和网络代码分开。通常,我更喜欢为每个独特的错误点提供独特的错误消息。您知道任何针对 Firebase 的解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 2020-01-03
    • 2021-05-09
    • 1970-01-01
    • 2020-04-19
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多