在NodeJS中不存在logging时捕获MySQL错误
我想弄清楚如何在数据库logging中找不到请求的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 catched 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)
节点 :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中处理exception。 你可以在这里阅读更多。
// Error handler app.use(function(err, req, res, next) { res.status(500).end(err.message); }); ... router.get('/users/:id(\\d+)', function(req, res, next) { var id = req.params.id; db.con.query('SELECT * FROM employees where id= ?', id, function (err, results) { if (err) return next(err); if (results.length == 0) return next(new Error('Incorrect id: ' + id)); obj = { id: results[0].id, name: results[0].name, location: results[0].location } res.render('showuser', obj); }); })