2011-11-26 88 views
7
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(之后),那么它会抓住它。

即使我把它嵌入到另一个函数中,我怎样才能让它抓住?

+1

什么是'insert_data( 'ABC'){抛出新的错误( '哈哈')}'应该是什么?这不是有效的语法。你的代码真的是什么样子? – RightSaidFred

+0

@RightSaidFred谢谢,修正。 – TIMEX

+0

@TIMEX你不能捕获异步环境的错误,它不会这样工作。停止使用'try catch' – Raynos

回答

6

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

问题是因为事件循环异步模型。您可以使用'uncaughtException'事件来捕获未捕获的错误,但它已成为Node.JS中常用的程序范例,使用回调函数的第一个参数来显示是否有任何错误,如下所示:从未使用过的MySQL与之前的NodeJS,只是做一般性的例子)

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!"); 
}); 
+0

这不是使用node.js的缺点之一。这是优点之一,你可以杀死try catch并使用'(err,data)'回调 – Raynos

+0

@Raynos我不明白为什么这是件好事?尝试捕捉是处理不可预见情况的consise成语......有一个参数在大多数情况下都是空的,似乎令人费解,并且像设计气味! –

+3

@DanielUpton尝试捕捉是丑陋的,它很慢,不会异步工作,并完全崩溃你的应用程序 – Raynos