javascript - How to catch error in node mySQL queries? - Stack Overflow

I use nodejs and mysql for my app. I do the DB query in such manner:try {myDB.query(SQL, object, (err,

I use nodejs and mysql for my app. I do the DB query in such manner:

try {
    myDB.query(SQL, object, (err, res) => {
        if (err) throw err
        ...
    }
} catch (err) {
    console.log(err.message)
}

But this is do not work because of async query func. So how to catch those errors, which is can occur in callback? Please help.

I use nodejs and mysql for my app. I do the DB query in such manner:

try {
    myDB.query(SQL, object, (err, res) => {
        if (err) throw err
        ...
    }
} catch (err) {
    console.log(err.message)
}

But this is do not work because of async query func. So how to catch those errors, which is can occur in callback? Please help.

Share Improve this question asked Oct 26, 2018 at 17:24 NastroNastro 1,7698 gold badges24 silver badges42 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 3

You can't throw inside of async code with callbacks. You must use async error handling:

function makeQuery(callback) {
  myDB.query(SQL, object, (err, res) => {
    if (err) {
      callback(err)

      return
    }

    ...
  }
}

It's up to the caller to provide a suitable callback function that takes (err, response) or something similar. It's also the responsibility of the caller to intercept, handle, or forward any and all errors.

If you use Promise-driven code you can either use .catch() or async functions with await that will work inside try. Sequelize is a good Promise-driven database driver.

Then you have code that looks like this:

let result = await myDB.query(SQL, object)

Which is obviously a lot cleaner.

You could use this example:

try {
  connection.query('SELECT * FROM ??',[Table], function (err) {
    if (err) console.error('err from callback: ' + err.stack);
  });
} catch (e) {
  console.error('err thrown: ' + err.stack);
}

for example. if "Table" does not exist, you would have the response:

'Table' doesn't exist

EDIT:

what @tadman says is correct, if you use if (err) throw err, you are only generating an exception error and you lose what you need.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745564660a4633319.html

相关推荐

  • javascript - How to catch error in node mySQL queries? - Stack Overflow

    I use nodejs and mysql for my app. I do the DB query in such manner:try {myDB.query(SQL, object, (err,

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信