2013-05-26 32 views
0

我正在使用https://github.com/felixge/node-mysql 并且每次mysql查询都会抛出一个错误,例如,如果一行不存在。节点服务器崩溃。NodeJS 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(); 

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

回答

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."); 
} 
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(); 

这是清洁海事组织和保证,我不会留下什么从if语句块中删除它不应该在的位置。