admin管理员组文章数量:1433161
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.
2 Answers
Reset to default 3You 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.
本文标签: javascriptHow to catch error in node mySQL queriesStack Overflow
版权声明:本文标题:javascript - How to catch error in node mySQL queries? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745564660a2663685.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论