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

Flutter中无法捕获FirebaseAuthException的问题及解决

FirebaseAuthException无法捕获的问题排查与解决

问题场景

尝试通过try-catch捕获Firebase登录时的FirebaseAuthException,但始终失败,控制台抛出未处理的异常。

错误代码

TextButton(
  onPressed: () async {
    try {
      final email = _email.text;
      final password = _password.text;

      final userCredential =
          FirebaseAuth.instance.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      print(userCredential);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print(e.message);
      }
    }
  },
  child: Text("Login"),
),

控制台输出

I/FirebaseAuth( 2241): Logging in as asdasdhas@gmail.com with empty reCAPTCHA token
E/RecaptchaCallWrapper( 2241): Initial task failed for action RecaptchaAction(action=custom_signInWithPassword)with exception - There is no user record corresponding to this identifier. The user may have been deleted.
E/flutter ( 2241): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.

问题原因

signInWithEmailAndPassword是异步方法,调用时未添加await关键字,导致代码直接返回Future<UserCredential>对象,不会等待异步操作完成并捕获其抛出的异常,异常最终以未处理的Future异常形式抛出。

修复方案

在调用signInWithEmailAndPassword时添加await关键字,确保异步操作完成后再执行后续代码,此时异常会被正确捕获到try-catch块中:

TextButton(
  onPressed: () async {
    try {
      final email = _email.text;
      final password = _password.text;

      final userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      print(userCredential);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print(e.message);
      }
    }
  },
  child: Text("Login"),
),

内容的提问来源于stack exchange,提问作者Alin Ahmet Tekin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:07:41