使用Firebase实现登录认证时try catch无法校验账号密码是否存在的问题
问题根因
auth.signInWithEmailAndPassword是Firebase Auth提供的异步方法,执行后会返回Promise实例,你当前使用的同步try/catch语句只能捕获同步代码抛出的错误,无法捕获异步任务的异常,所以错误只会输出到控制台,不会触发catch分支的前端提示逻辑。
修复方案
方案1:搭配async/await语法使用try/catch
给handleLogin方法添加async修饰符,调用login方法前加await关键字等待异步执行完成,即可用现有try/catch捕获错误:
function login(email, password) { return auth.signInWithEmailAndPassword(email, password); } const handleLogin = async (e) => { e.preventDefault(); try { setError("") await login(emailRef.current.value, passwordRef.current.value); } catch { // 可根据业务需求替换为中文提示:您输入的邮箱或密码不正确 setError("The email or password you entered is incorrect"); } }
方案2:使用Promise自带的catch方法捕获异常
无需修改原login方法,直接在调用后链式调用.catch处理错误即可:
const handleLogin = (e) => { e.preventDefault(); setError("") login(emailRef.current.value, passwordRef.current.value) .catch(() => { setError("The email or password you entered is incorrect"); }) }
拓展说明
如果需要区分不同错误类型返回更精准的提示,可以在catch分支中获取错误对象的code属性判断:
常见错误码包括:
auth/user-not-found:邮箱未注册auth/wrong-password:密码错误auth/invalid-email:邮箱格式不合法
内容的提问来源于stack exchange,提问作者Zeamanuel Belay
相关产品推荐
相关产品推荐

