繁体   English   中英

当用户更新密码时,如何捕获 Firebase Auth 返回的特定错误?

[英]How do I catch specific error returned by Firebase Auth, when user updates their password?

我正在编写一个应用程序,我想让用户可以更改他们的密码。 所以我有一个简单的UpdatePassword.js页面,我在其中调用 Firebase Authentication .updatePassword(password)方法。 如文档中所述,这是一项敏感操作,因此,用户需要进行身份验证(如果他们最近没有进行身份验证),以便将密码更改为新密码。

这是我的方法:

const update = async () => {
    const user = await firebase.auth().currentUser;
    await user
      .updatePassword(password)
      .then(() => {
        setUpdated(true);
      })
      .catch((error) => {
        //I want to handle this specific error but I don't know how
        if (
          error.message ===
          "This operation is sensitive and requires recent authentication. Log in again before retrying this request."
        ) {
          console.log("should display a modal for user to authenticate again");
        }
        console.log("error while updating pass: ", error);
        setSaving(false);
      });
  };

正如您从我的console.log中看到的那样,在用户需要再次进行身份验证的情况下,我想显示一个模式,他们将在其中再次使用他们的凭据登录。 这不是问题,而且很容易做到。 但是,我的问题是,如何在用户需要进行身份验证的情况下捕获这种特定类型的错误? 根据我的console.log ,我现在实现它的方式,我只是比较从Firebase Authentication收到的错误消息,这确实不是正确的方法。 如果 Firebase Auth 将错误消息更改为其他内容怎么办? 是否有类似错误代码的东西,我可以将其与引发的错误进行比较,并通过错误代码或比字符串消息更安全的东西处理异常?

正如您将在文档中看到的那样,在这种情况下引发的错误(即“如果用户的上次登录时间未达到安全阈值”)具有auth/requires-recent-login错误代码。

所以:

//...
.catch((error) => {
     if (error.code === 'auth/requires-recent-login') {
         // Display the modal 
     } else {
         // ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM