NodeJS Mysql停止服务器崩溃时出错

时间:2013-05-26 14:07:22

标签: mysql node.js locomotivejs

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

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();

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

2 个答案:

答案 0 :(得分:0)

如果发生错误,您的代码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.");
}

答案 1 :(得分:0)

我更喜欢使用return声明:

connection.connect();

connection.query('SELECT * from table1 where id = 2',  function(err, rows, fields) {
  if (err) return console.log(err);

  if (rows[0]) { 
    console.log('The result is  ', rows[0].user);
  }
});
connection.end();

这是更清洁的IMO,并保证我不会在if语句块中留下任何不应该的东西。