【问题标题】:Meteor: How to catch asynchronous callback function errorsMeteor:如何捕获异步回调函数错误
【发布时间】:2014-12-01 16:31:09
【问题描述】:

我正在尝试捕获异步函数中可能引发的错误。

我尝试过使用fibers包,但是安装了这个包后,app不会开始报这个错误:

=> 错误阻止启动:

在构建应用程序时:

node_modules/fibers/build.js:1:15:意外令牌非法

所以我放弃了这个包(这也意味着Future类)......

我也尝试用Meteor.wrapAsync 包装回调函数,但这也不起作用。

这是我正在使用的代码:

try {
    Meteor.users.update({
        _id: this.user_id
    },{
        $set: {first_name: "test"}
    },{
        multi: false
    }, function(error, response){
        if(response < 1)
            throw "user could not be updated!";
    });

    console.log('user updated');
}
catch(error) {
    console.log('catched');
    console.error(error);
}

由于回调函数是异步的,因此不会被捕获,因为在抛出错误时捕获块代码已经运行。我只是想找出一种方法来捕捉我抛出的错误。

【问题讨论】:

  • 这是在客户端还是服务器上?
  • @user3374348 这是在服务器上

标签: javascript asynchronous meteor asynccallback


【解决方案1】:

在服务器上,collection.update 已经可以同步使用了。所以你需要做的就是:

try {
  var documentsAffected = Meteor.users.update({
      _id: this.user_id
  },{
      $set: {first_name: "test"}
  },{
      multi: false
  });

  if (documentsAffected < 1) {
    throw new Error("user could not be updated!");
  }

  console.log("user updated");

} catch (error) {
  // will also catch exceptions thrown by Meteor.users.update
  console.log("caught an error!");
  console.error(error);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 2022-01-14
    • 2016-09-10
    • 2021-10-20
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多