在NodeJS中不存在记录时捕获MySQL错误

时间:2017-12-07 18:47:41

标签: mysql node.js express

我试图找出在数据库记录中找不到请求的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)

节点:v8.8.0

快递:v4.15.5

2 个答案:

答案 0 :(得分:3)

试试这个:

try{
  obj = {
     id: results[0].id,
     name: results[0].name,
     location: results[0].location
  }
}catch(err){
  //handle error
}

try {...}catch...是如何处理JavaScript中的异常的。您可以阅读更多相关信息here.

答案 1 :(得分:0)

// 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);
    });
})