Async Functions with Try-Catch Error Handling
suggest changeOne of the best features of async/await syntax is that standard try-catch coding style is possible, just like you were writing synchronous code.
const myFunc = async (req, res) => {
try {
const result = await somePromise();
} catch (err) {
// handle errors here
}
};
Here’s an example with Express and promise-mysql. It assumes pool is a promise-mysql pool:
router.get('/flags/:id', async (req, res) => {
try {
const connection = await pool.getConnection();
try {
const sql = `SELECT f.id, f.width, f.height, f.code, f.filename
FROM flags f
WHERE f.id = ?
LIMIT 1`;
const flags = await connection.query(sql, req.params.id);
if (flags.length === 0)
return res.status(404).send({ message: 'flag not found' });
return res.send(flags[0]);
} finally {
connection.release();
}
} catch (err) {
// handle errors here
}
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents