如何捕获Firebase Auth用户更新密码时的特定需重认证错误?
用Firebase Auth错误码可靠捕获重新认证需求
Firebase Authentication的错误对象包含稳定的code属性,相比易变的错误消息,用错误码判断是更可靠的方式。针对你遇到的"需要近期认证"的场景,对应的错误码是auth/requires-recent-login。
修改你的代码如下:
const update = async () => { const user = firebase.auth().currentUser; // currentUser是同步属性,无需await user .updatePassword(password) .then(() => { setUpdated(true); }) .catch((error) => { // 用错误码判断,替代不可靠的消息文本 if (error.code === 'auth/requires-recent-login') { console.log("should display a modal for user to authenticate again"); } console.log("error while updating pass: ", error); setSaving(false); }); };
注意:firebase.auth().currentUser是同步获取的属性,不需要用await修饰。当捕获到该错误后,你可以调用user.reauthenticateWithCredential()方法让用户重新完成认证(比如通过邮箱密码、第三方登录凭证等),认证成功后再重新执行密码修改操作。
内容的提问来源于stack exchange,提问作者newbie coder
相关产品推荐
相关产品推荐

