使用 Try-Catch 錯誤處理的非同步函式
async / await 語法的最佳功能之一是可以使用標準的 try-catch 編碼樣式,就像編寫同步程式碼一樣。
const myFunc = async (req, res) => {
try {
const result = await somePromise();
} catch (err) {
// handle errors here
}
});
這是 Express 和 promise-mysql 的一個例子:
router.get('/flags/:id', async (req, res) => {
try {
const connection = await pool.createConnection();
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 {
pool.releaseConnection(connection);
}
} catch (err) {
// handle errors here
}
});