Home > database >  NodeJS Express: MySQL syntax error thrown but I cannot catch it on try-catch
NodeJS Express: MySQL syntax error thrown but I cannot catch it on try-catch

Time:06-18

I have this controller:

//http://127.0.0.1:3000/user
router.get('/', function(req, res) {

  try {
    var result = userDao.findAll();

    res.send('Users home page');
  } catch (err) {
    console.log("I EXPECTED THIS TEXT TO SHOW UP WHEN FORCING A MYSQL SINTAX ERROR");
  }

});

and this findAll() function on userDao file:

function findAll() {

    con.query("SELECTTTTTT * FROM user WHERE name = ?", ["Anna"], function (err, result) {
        if (err) throw err;

    });
}

As you can see on my query, I'm forcing an error to be thrown. So I was expecting to see the text I EXPECTED THIS TEXT TO SHOW UP.... on my console, instead I see the error stacktrace. Any help?

CodePudding user response:

you can not catch the error since it's been thrown inside an async function try this instead:

router.get('/', async (req, res) => {
  try {
    var result = await userDao.findAll();

    res.send('Users home page');
  } catch (err) {
    console.log(
      'I EXPECTED THIS TEXT TO SHOW UP WHEN FORCING A MYSQL SINTAX ERROR'
    );
  }
});

in your userDao:

function findAll() {
  return new Promise((resolve, reject) => {
    con.query(
      'SELECTTTTTT * FROM user WHERE name = ?',
      ['Anna'],
      function (err, result) {
        if (err) reject(err);
        else resolve(result);
      }
    );
  });
}

This way you can catch the error.

  • Related