gpt4 book ai didi

mysql - NodeJS Mysql 停止服务器因错误而崩溃

转载 作者:行者123 更新时间:2023-11-30 01:36:52 25 4
gpt4 key购买 nike

我正在使用https://github.com/felixge/node-mysql每次 mysql 查询都会抛出错误,例如,如果一行不存在。 Node 服务器崩溃。

connection.connect();

connection.query('SELECT * from table1 where id = 2', function(err, rows, fields) {
if (err) console.log(err);
if (rows[0]) {
console.log('The result is ', rows[0].user);
}
});
connection.end();

如何简单地将错误打印到页面而不使服务器崩溃。

最佳答案

如果发生错误,您的代码 console.log 就是错误,但仍会尝试访问 rows[0]。如果出现错误,rows 将未定义,因此 rows[0] 将触发新错误。

使用 else 结合长度检查可以轻松修复:

if (err) {
console.log(err);
} else if (rows.length) {
console.log('The result is ', rows[0].user);
} else {
console.log("Query didn't return any results.");
}

关于mysql - NodeJS Mysql 停止服务器因错误而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com