0

I'm trying to catch an error that could be thrown in an asynchronous function.

I have tried using the fibers package, but after the installation of this package, the app won't start giving this error:

=> Errors prevented startup:

While building the application:

node_modules/fibers/build.js:1:15: Unexpected token ILLEGAL

So I gave up on this package (this means also on the Future class)...

I also tried to wrap the callback function with Meteor.wrapAsync, but this doesn't do the trick either.

This is the code I'm working with:

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

Since the callback function is asynchronous it won't be catched because the catch block code will already have run when the error is thrown. I'm just trying to figure out a way to catch the error I throw.

Hans Vn
  • 787
  • 1
  • 16
  • 32

1 Answers1

1

On the server, collection.update can already be used synchronously. So all you need to do is:

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);
}
user3374348
  • 4,101
  • 15
  • 29