簡體   English   中英

流星:如何捕獲異步回調函數錯誤

[英]Meteor: How to catch asynchronous callback function errors

我正在嘗試捕獲可能在異步函數中引發的錯誤。

我已經嘗試過使用Fibers軟件包,但是在安裝了此軟件包之后,該應用程序將不會開始出現此錯誤:

=>錯誤阻止啟動:

在構建應用程序時:

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);
}

由於回調函數是異步的,因此不會被捕獲,因為拋出錯誤時,catch塊代碼將已經運行。 我只是想找出一種方法來捕獲我拋出的錯誤。

在服務器上, 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM