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
,我有:node.js如何避免我的錯誤?
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)
注意到,如果我把扔的權利的do_stuff(之後),那麼它會抓住它。
即使我把它嵌入到另一個函數中,我怎樣才能讓它抓住?
什麼是'insert_data( 'ABC'){拋出新的錯誤( '哈哈')}'應該是什麼?這不是有效的語法。你的代碼真的是什麼樣子? – RightSaidFred
@RightSaidFred謝謝,修正。 – TIMEX
@TIMEX你不能捕獲異步環境的錯誤,它不會這樣工作。停止使用'try catch' – Raynos