typescript - 如何控制firebase函数中抛出错误的输出
问题描述
我在我的 firebase 函数中使用 async/await,每个调用都有可能引发错误。我不确定如何正确处理捕获每个错误。我不想将每个调用都包装在 try/catch 中,因为所涉及的代码量几乎违背了使用 await 语法的目的。
如果我让等待抛出,那么 firebase-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 }
推荐阅读
- javascript - Discord.js:无法读取 Null 的属性“名称” - 如何解决此问题?
- python - 使用内部连接连接两个数据框
- ms-access - 我可以重新分发 dao360.dll 和 acedao.dll 吗?
- excel - 运行单个命令时如何解决“无响应”
- c - C 网络:Sendto() 返回 Errno 22、EINVAL
- amazon-web-services - DynamoDB 地图中的随机字符
- html - 如何让网页无响应?
- c++ - c++ set_intersection 具有相同输入的不同结果
- ios - 使用 MSMessageLiveLayout 时如何更新 MSMessage URL?
- firebase - 如何检查电子邮件地址是真实的还是虚假的