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

402 Views Asked by At

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?

3

There are 3 best solutions below

0
Little Brain On BEST ANSWER

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', '[email protected]', 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");
}
1
Dmitrijs Balcers On

You can read the information about what this method does here: https://github.com/meteor/meteor/blob/master/packages/accounts-password/password_server.js#L847

As you can see, the method will fail only in one case:

The operation will fail if there is a different user with an email only differing in case

Therefore if the method fails you can tell to the user that the email is already registered.

0
glennn On

I know I'm a bit late to the party but I ran into this problem today and found your post.

I needed to be able to tell on the server side whether it failed or not so what I did was put it in a try-catch like so:

let addSucceeded = false;

try{
    Accounts.addEmail(user._id, newEmailAddress);
    addSucceeded = true;
} catch(err) {}

console.log(addSucceeded);

Only if the Accounts.addEmail does not fail will addSucceeded be set to true. To make sure I don't run into the "fail because it replaced the same user's email address in a different case" scenario, I always toLowerCase() the email address when saving.