Home Catch MySQL error when record does not exist in NodeJS
Reply: 0

Catch MySQL error when record does not exist in NodeJS

user1151
1#
user1151 Published in April 20, 2018, 10:47 am

I am trying to figure out how I can catch an error when a requested id is not found in the Database records.

My code is

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

});

In console I get the following error when a non-existed id is requested as it should be, however I cannot catch this error programatically.

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.31275 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO