如何判断Accounts.addEmail成功还是失败,如果失败,原因

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

我有一个页面,用户可以在其中输入新的电子邮件地址,然后此方法会尝试将其添加到他们的帐户中:

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

我正在使用 Meteor 中的帐户密码包。

我想在用户尝试添加新地址后向他们提供有意义的反馈,特别是如果失败,为什么会失败?我看过 docs 但似乎没有任何方法可以找出失败原因。

我知道我可以在尝试添加新地址之前和之后计算用户的电子邮件地址,但这并不能告诉我该地址是否已经属于另一个用户,或者它是否是该用户的现有地址,或任何失败原因。

有什么方法可以找出这样的 API 调用的结果吗?

您可以在此处阅读有关此方法的作用的信息: https://github.com/meteor/meteor/blob/master/packages/accounts-password/password_server.js#L847

如您所见,该方法只会在一种情况下失败:

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

因此,如果该方法失败,您可以告诉用户该电子邮件已经注册。

经过更多的试验,似乎我需要做的就是在调用该方法时向我的客户端添加一个回调,并在那里检查是否有错误。任何错误都会自动返回给回调。

服务器:

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

客户:

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

我没有意识到来自 API 的错误会传递到我的方法中。 Meteor - 它总是比我想象的更聪明!

另请注意,您可以在方法中使用 Meteor.Error 来抛出错误,这些错误将以完全相同的方式传递给客户端回调,请参阅 docs:

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

我知道我参加派对有点晚了,但我今天 运行 解决了这个问题并找到了你的 post。

我需要能够在服务器端判断它是否失败,所以我所做的就是像这样将它放在 try-catch 中:

let addSucceeded = false;

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

console.log(addSucceeded);

只有 Accounts.addEmail 没有失败才会将 addSucceeded 设置为 true。为了确保我不会 运行 进入 "fail because it replaced the same user's email address in a different case" 场景,我在保存时总是 toLowerCase() 电子邮件地址。