apimeteoraccountsuser-feedback

How to tell whether Accounts.addEmail succeeded or failed, and if it failed, the reason why


I have a page where the user can type in a new email address and then this method attempts to add it to their account:

Meteor.methods({
  add_new_email: function(address)
  {
    Accounts.addEmail(Meteor.userId(), address);
  }
});

I'm using the accounts-password package in Meteor.

I'd like to give the user meaningful feedback after they try to add the new address, in particular if it failed why did it fail? I have looked at the docs but there doesn't seem to be any method to find out failure reason.

I know that I can count the user's email addresses before and after trying to add the new one, but that doesn't tell me if the address already belongs to another user, or if it's an existing address of the user's, or whatever is the failure reason.

Is there any way to find out the result of an API call like this?


Solution

  • After experimenting some more, it seems that all I need to do is add a callback to my client when I call the method, and check there for an error. Any error is automatically returned to the callback.

    Server:

    Meteor.methods({
      add_new_email: function(address)
      {
        Accounts.addEmail(Meteor.userId(), address);
      }
    });
    

    Client:

    Meteor.call('add_new_email', 'me@example.com', function(error){
      if (error) console.log("got an error " + error.reason);
    });
    

    I had not realised that the error from the API would be passed up into my method. Meteor - it's always more clever than I expect!

    Note also that you can use Meteor.Error in your methods to throw errors which will be passed up to client callbacks in exactly the same way, see the docs:

    if (!Meteor.userId()) {
      throw new Meteor.Error("not-authorized", "You must be signed in to write a new post");
    }