Задача . Гигантский try / catch:
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 }