为什么node.js没有发现我的错误?

TIM*_*MEX 7 javascript debugging error-handling exception 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!
}
Run Code Online (Sandbox Code Playgroud)

在里面do_stuff,我有:

function do_stuff(){
    //If I put the throw here, it will catch it! 
    insert_data('abc',function(){
        throw new Error('haha');
    });
}
Run Code Online (Sandbox Code Playgroud)

为什么它永远不会记录'抓住错误'?相反,它将堆栈跟踪和错误对象打印到屏幕:

{ 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)
Run Code Online (Sandbox Code Playgroud)

请注意,如果我在do_stuff()之后抛出RIGHT,那么它将捕获它.

即使我把它嵌套在另一个函数中,我怎么能抓住它?

Nic*_*can 6

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

问题是因为事件循环异步模型.您可以使用' uncaughtException '事件来捕获未捕获的错误,但它已成为Node.JS中的常用程序范例,使用回调函数的第一个参数来显示是否存在任何错误,如下所示:(I之前从未使用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!");
});
Run Code Online (Sandbox Code Playgroud)

  • @DanielUpton尝试捕获是丑陋的,它很慢,因为地狱,不能异步工作并完全崩溃您的应用程序 (4认同)
  • @Raynos尝试捕获不会崩溃您的应用程序.它的目的不是让您的应用程序崩溃."地狱慢",我不知道这件事. (2认同)
  • 这里的每个人都偏离了目标。阅读一些有关 Promise/async/await 的内容 — 这是未来的发展方向。是的,async/await 现在允许 try/catch 块在异步代码上工作,这非常优雅 (2认同)