【问题标题】:How come node.js doesn't catch my errors?为什么 node.js 没有捕捉到我的错误?
【发布时间】: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


【解决方案1】:

这是使用 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!");
});

【讨论】:

  • 这不是使用 node.js 的缺点之一。这是优点之一,您可以杀死 try catch 并使用 (err, data) 回调
  • @DanielUpton try catch 很丑,它慢得要命,不能异步工作并且完全崩溃你的应用程序
  • @Raynos try catch 不会使您的应用程序崩溃。它的目的不是使您的应用程序崩溃。 “慢得要命”,我不知道。
  • 底线;异步模型中的 try-catch 不是可靠的模式。但是, .catch( function(err){...} );应该作为 Promise 设计模式工作,但是唉......似乎相当随意:\
  • 这里的每个人都离题了。阅读一下 promises/async/await ——这是未来的发展方向。是的,async/await 现在允许 try/catch 块处理异步代码,这非常优雅
猜你喜欢
  • 2019-05-16
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 2021-07-25
  • 2017-07-25
  • 2022-08-15
相关资源
最近更新 更多