为什么Node.js不能捕捉到我的错误?

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'); }); } 

它怎么从来没有logging“发现错误”? 相反,它将堆栈跟踪和错误对象打印到屏幕上:

 { 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 RIGHT放在do_stuff()之后,那么它会捕获它。

即使我把它embedded到另一个函数中,我怎么能把它抓住呢?

这是使用NodeJS的一个缺点。 它基本上有两种处理错误的方法; 一个通过使用try / catch块,另一个通过传递每个callback函数的第一个参数作为错误。

问题是由于事件循环asynchronous模型。 您可以使用' uncaughtException '事件来捕获没有被捕获的错误,但是它已经成为Node.JS中一个常用的程序范例,使用callback函数的第一个参数来显示是否有任何错误,如下所示:以前从未使用过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!"); });