gpt4 book ai didi

javascript - 如何处理 firebase.auth.PhoneAuthProvider.credential 错误

转载 作者:行者123 更新时间:2023-12-03 00:25:14 25 4
gpt4 key购买 nike

我正在使用 firebase 电话身份验证 对 Firebase 上的用户进行身份验证。它工作正常,在使用 xyz 电话号码成功验证用户身份后,现在我想将电话号码更新为 abc,简而言之,我正在尝试更新用户的手机号码。我发现 firebase web api 可以更新用户现有的手机号码,其工作原理如下。

以下函数将向用户想要注册的新电话号码发送 otp。

function sentOTPToNewNumber() {
var phoneNumber = document.getElementById("newPhone").value;
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {

// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).

window.confirmationResult = confirmationResult;
}).catch(function (error) {
console.log(error)
});
}

收到新号码的 otp 后,我们必须验证以下功能的号码是否正在执行此操作。

    function codeVerification() {
var verificationCode = document.getElementById("verification").value;


try {
//at this line i am facing issue.
var credential = firebase.auth.PhoneAuthProvider.credential(confirmationResult.verificationId, verificationCode)

console.log(credential);
var result = userLocal.updatePhoneNumber(credential);
console.log(result);
} catch (error) {
console.log(error);
}
}

我想在用户在 codeVerification 函数中输入错误的 otp 时处理错误。当我们尝试输入错误的 otp 时,我们使用的以下 api 会抛出错误,但我无法在 try catch< 中处理错误 阻止。

firebase.auth.PhoneAuthProvider.credential(confirmationResult.verificationId, verificationCode)

我在google firebase上找到了以下描述但无法理解如何处理错误。我实现的 try catch block 没有捕获 firebase 抛出的错误。我还尝试使用 then(function(){}).catch(function(error){}) 它说 then 不是一个函数。 enter image description here

我的控制台出现以下错误,我想处理它。注意:如果用户输入正确的 otp,我能够成功更新用户电话号码。唯一的问题是我想处理代码不正确的情况或知道更新是否成功。

enter image description here

感谢您的宝贵时间和支持,这将非常有帮助。

最佳答案

userLocal.updatePhoneNumber(credential) 调用返回一个 Promise 对象(请参阅 updatePhoneNumber docs ),当出现问题时该对象会被拒绝。但是,您 try catch 此错误的方式是不正确的,这就是您无法正确处理错误的原因。

要处理 Promise 拒绝,请在 userLocal.updatePhoneNumber 之后链接 .then().catch(),如下所示:

userLocal.updatePhoneNumber(credential)
.then(/* Update successful */)
.catch(function(error) {
// Update failed
});

如果您在代码中使用 async/await,则可以保留当前的 ​​try-catch 代码,但执行以下更改:

  1. 使 codeVerification 成为 async 函数
  2. 等待userLocal.updatePhoneNumber的调用
async function codeVerification() {
...
try {
...
var result = await userLocal.updatePhoneNumber(credential);
// ^^^^^ notice the `await` keyword above
// Update successful
} catch (error) {
// Update failed
}
}

以上两种解决方案基本相同,只是语法不同。

关于javascript - 如何处理 firebase.auth.PhoneAuthProvider.credential 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54123927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com