-1

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 cached here when a requested results[0].id is not found
            }
            res.render('showuser');
        }
    })

});

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

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

1
  • try printing the id using console.log(req.params.id) which will help you to see if the id is defined or not... plus initialize your getId variable var getId. add ; at the end of the statement. Commented Dec 7, 2017 at 18:56

3 Answers 3

2

Try this:

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

try {...}catch... is how you handle exceptions in JavaScript. You can read more about it here.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

What does (\\d+) stand for in router.get ?
@Cadmos it means :id must be a number (\d) and it's length must be greater than 0 (+)
1

Try the code below:

router.get('/product/:id', function(req, res, next){
        try {
            const { idProduct } = req.body
            const [detailProduct] = await Product.detail(idProduct);
            if (detailProduct.length === 0) {
                return res.status(404).send({
                    status: "404",
                    msg: "Not found",
                    data: null
                });
            }
            return res.status(200).json(detailProduct[0])
        } catch (error) {
            if (!error.statusCode) {
                error.statusCode = 500
            }
            next(error)
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.