var api_friends_helper = require('./helper.js');
try{
api_friends_helper.do_stuff(function(result){
console.log('success');
};
}catch(err){
console.log('caught error'); //this doesn't hit!
}
还有里面do_stuff
, 我有:
function do_stuff(){
//If I put the throw here, it will catch it!
insert_data('abc',function(){
throw new Error('haha');
});
}
为什么它从不记录“捕获错误”?相反,它将堆栈跟踪和错误对象打印到屏幕上:
{ stack: [Getter/Setter],
arguments: undefined,
type: undefined,
message: 'haha' }
Error: haha
at /home/abc/kj/src/api/friends/helper.js:18:23
at /home/abc/kj/src/api/friends/db.js:44:13
at Query.<anonymous> (/home/abc/kj/src/node_modules/mysql/lib/client.js:108:11)
at Query.emit (events.js:61:17)
at Query._handlePacket (/home/abc/kj/src/node_modules/mysql/lib/query.js:51:14)
at Client._handlePacket (/home/abc/kj/src/node_modules/mysql/lib/client.js:312:14)
at Parser.<anonymous> (native)
at Parser.emit (events.js:64:17)
at /home/abc/kj/src/node_modules/mysql/lib/parser.js:71:14
at Parser.write (/home/abc/kj/src/node_modules/mysql/lib/parser.js:576:7)
请注意,如果我将 throw 放在 do_stuff() 之后,那么它会捕获它。
即使我将其嵌套在另一个函数中,如何才能使其捕获?
这是使用 NodeJS 的缺点之一。它基本上有两种处理错误的方法;一种是通过使用 try/catch 块,另一种是通过将每个回调函数的第一个参数作为错误传递。
问题是由于事件循环异步模型造成的。您可以使用 '未捕获的异常 http://nodejs.org/docs/v0.6.3/api/process.html#event_uncaughtException_' 事件来捕获未捕获的错误,但使用回调函数的第一个参数来显示是否有任何错误已成为 Node.JS 中常见的程序范例,如下所示:(我以前从未在 NodeJS 中使用过 MySQL ,只是举一个一般的例子)
function getUser( username, callback ){
mysql.select("SELECT username from ...", function(err,result){
if( err != null ){
callback( err );
return;
}
callback( null, result[0]);
});
}
getUser("MyUser", function(err, user){
if( err != null )
console.log("Got error! ", err );
else
console.log("Got user!");
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)