是否应该将每个数据库查询都封装在try/catch块中



如果我的控制器在同一异步函数中进行多个数据库查询,每个数据库查询应该封装在它自己的单独try/catch块中,还是将所有数据库查询都放在同一try/catch中?这两种选择的理由是什么?

所有数据库查询都有自己的try/catch示例:

const confirmEmailVerification = async (req, res) => {
const { token } = req.body;
let user;
try {
const result = await db.query(
'SELECT user_account_id FROM user_account WHERE email_verification_token = $1',
[token]
);
if (result.rows.length === 0) {
return res
.status(400)
.json('Please verify your account by clicking the link in your email');
}
user = result.rows[0].user_account_id;
} catch (err) {
console.error(err.message);
return res.status(500).json('Server Error');
}
try {
const active = await db.query(
'UPDATE user_account SET email_verified = TRUE WHERE user_account_id = $1',
[user]
);
return res.status(200).json({
message: 'Email has been verified, Please login',
});
} catch (err) {
console.error(err.message);
return res.status(500).json('Server Error');
}
};

同一try/catch示例中的所有数据库查询:

const confirmEmailVerification = async (req, res) => {
const { token } = req.body;
let user;
try {
const result = await db.query(
'SELECT user_account_id FROM user_account WHERE email_verification_token = $1',
[token]
);
if (result.rows.length === 0) {
return res
.status(400)
.json('Please verify your account by clicking the link in your email');
}
user = result.rows[0].user_account_id;
const active = await db.query(
'UPDATE user_account SET email_verified = TRUE WHERE user_account_id = $1',
[user]
);
return res.status(200).json({
message: 'Email has been verified, Please login',
});
} catch (err) {
console.error(err.message);
return res.status(500).json('Server Error');
}
};

如果您希望函数序列在前一个函数抛出错误后继续,这取决于此。在您的情况下,它是无用的,因为在任何一个错误中,您都会以res.status(500).json('Server Error')结束。但有时你想继续,即使链中的一些函数抛出错误,例如:

let errors = []
try {
f1()
} catch (e) {
errors.push(e)
}
try {
f2()
} catch (e) {
errors.push(e)
}
try {
f3()
} catch (e) {
errors.push(e)
}

如果你把这个放在一个try/catch块中,你会在f1()f2()的错误上停止,f3()根本不会运行。

try {
f1()
f2()
f3()
} catch (e) {
something... 
}

相关内容

  • 没有找到相关文章

最新更新