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



我正在编写一个应用程序,我想让用户可以更改密码。因此,我有一个简单的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 {
// ...

最新更新