我正在尝试找出当在数据库记录中找不到请求的 id
时如何捕获错误。
我的代码是:
router.get('/users/:id', function(req, res) {
getId = req.params.id
db.con.query('SELECT * FROM employees where id=?', getId, function(err, results) {
if (err) {
console.log('error in query')
return
} else {
obj = {
id: results[0].id,
name: results[0].name,
location: results[0].location
// error should be cached here when a requested results[0].id is not found
}
res.render('showuser');
}
})
});
在控制台中,当请求不存在的 id
时出现以下错误,但我无法以编程方式捕获此错误。
throw err; // Rethrow non-MySQL errors
^
ReferenceError: id is not defined
at Query._callback (C:\NodeJS\CRUD\CRUD-4\routes\add.js:21:13)
Node :v8.8.0
Express:v4.15.5
最佳答案
试试这个:
try{
obj = {
id: results[0].id,
name: results[0].name,
location: results[0].location
}
}catch(err){
//handle error
}
try {...}catch...
是您在 JavaScript 中处理异常的方式。您可以阅读更多相关信息 here.
关于mysql - 当 NodeJS 中不存在记录时捕获 MySQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47701803/