You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中捕获错误后console.log无输出问题求助

问题解决:Firebase登录错误console.log无输出、notify无法接收的问题

核心问题分析

Firebase的signInWithEmailAndPassword抛出的错误是自定义Error对象,直接console.log(error)只会打印对象结构,而alert(error)能正常显示是因为alert会自动调用对象的toString()方法(Firebase重写了这个方法返回错误消息)。另外你的第二种写法里还有个笔误:alert(err)应该是alert(error)。

修正后的代码示例

第一种写法(Promise链式调用)

const signIn = (e) => {
    e.preventDefault();
    signInWithEmailAndPassword(auth, email, password)
      .then(() => {
        navigate("/");
      })
      .catch((error) => {
        // 获取具体错误信息和错误码
        const errorMessage = error.message;
        const errorCode = error.code;
        
        console.log("错误码: ", errorCode);
        console.log("错误消息: ", errorMessage);
        alert(errorMessage);
        notify(errorMessage); // 现在可以正常传递错误消息
      });
};

第二种写法(async/await + try-catch)

async function signIn(e) {
  try {
    e.preventDefault();
    await signInWithEmailAndPassword(auth, email, password);
    navigate("/"); // 这里不需要嵌套then,await已经处理了异步
  } catch (error) {
    const errorMessage = error.message;
    const errorCode = error.code;
    
    console.error("错误码: ", errorCode);
    console.error("错误消息: ", errorMessage);
    alert(errorMessage);
    notify(errorMessage);
  }
}

关键说明

  • Firebase Auth的错误对象包含code(如auth/user-not-found)和message(用户友好的错误提示)两个核心属性,直接访问这两个属性就能拿到你需要的信息。
  • 第二种写法里不需要在await后嵌套.then(),await会等待Promise完成,之后直接写navigate逻辑即可,代码更简洁。

内容的提问来源于stack exchange,提问作者kamels90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:35:13