【发布时间】:2012-01-06 17:58:01
【问题描述】:
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() 之后,那么它将捕获它。
即使我把它嵌套在另一个函数中,我怎样才能让它被捕获?
【问题讨论】:
-
insert_data('abc'){ throw new Error('haha') }应该是什么?那不是有效的语法。你的代码到底是什么样子的? -
@RightSaidFred 谢谢,已修复。
-
@TIMEX 您无法捕获异步环境的错误,它不会那样工作。停止使用
try catch -
@Raynos 那么我如何在 Node.js 中捕获错误呢?
-
@TIMEX 在回调中使用
err参数
标签: javascript debugging exception node.js error-handling