提问人:Henry Boyer 提问时间:9/20/2022 更新时间:9/20/2022 访问量:78
使用 try...catch 在 Express 后端正确处理错误
Using try...catch to handle errors properly in express backend
问:
我已经使用 Express 制作后端 API 一段时间了。我最近意识到我大大低估了我需要做的错误处理量,我想在修复我的 API 之前确保我做对了。
下面是一个示例:
router.post('/example', function(req,res,next){
//try...catch is not needed here because express automatically places routes in a try...catch
QueryDatabase('SELECT * FROM accounts WHERE uuid = ?', req.session.uuid, (err, result) => {
//Assuming QueryDatabase uses asychronous callback there needs to be another try...catch in the callback
if (err) return next(err);
try {
let email = result[0].email;
//Assuming HideEmail uses sychronous callback there does not need to be another try...catch because the outer try catch will catch errors
HideEmail(email, (err, result) => {
if (err) return next (err);
let hiddenEmail = result;
//Assuming GetVerified uses asychronous callback there still does not need to be try catch because no error could be thrown.
//(although maybe one should still be added im not too sure)
GetVerified(email, (err, result) => {
if (err) return next (err);
res.send({email:hiddenEmail, verified:result});
})
})
} catch (error) {
next(error);
}
})
})
这样做并保留我的所有代码都包含在尝试中是个好主意吗?捕获某种内容,当使用异步回调进行另一次尝试时......也抓到?我觉得这是最安全的选择,这样 API 就不会因未处理的错误而崩溃,但我是新手,对我在做什么不太了解。
答: 暂无答案
评论
try/catch
try/catch
QueryDatabase()
HideEmail()
GetVerified()