Challenge. Dealing with a large try/catch block:
module.exports = async (req, res) => {
// Obtain the data from the request
const input1 = req.body.input1
const input2 = req.body.input2
try {
// Initially await for file information
const fileInfo = await db.getFileInfo(input2)
// Perform some synchronous operations
const tempFilePath = generateUniqueTempFilePath(fileInfo)
// Further asynchronous actions
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)
}
}
One approach is to encapsulate all await calls and related logic in a separate function, centralizing the try/catch block within the endpoint method.
Illustration. Minimal try/catch and a dedicated function:
const service = require('./serviceA')
module.exports = async (req, res) => {
// Obtain the data from the request
const input1 = req.body.input1
const input2 = req.body.input2
// Execute asynchronous 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)
}
and
async function perform (input1, input2) {
// Initial async operation (no try/catch needed!)
const fileInfo = await db.getFileInfo(input2)
// Perform some synchronous work
const tempFilePath = generateUniqueTempFilePath(fileInfo)
// Additional async tasks (ensure they throw errors with appropriate messages!)
await storage.download(input1, tempFilePath)
const checkinResult = await db.checkin(tempFilePath, data)
return { checkinResult, fileInfo }
}
module.exports = { perform }