【问题标题】:I can't catch the exception of Firebase Auth on flutter我在颤动时无法捕捉到 Firebase Auth 的异常
【发布时间】:2021-02-12 15:50:37
【问题描述】:

我正在尝试在 Flutter 上使用 Firebase 身份验证在我的应用上创建登录功能。

我必须处理许多异常,但我根本无法捕获它们。

这是我的代码。

Future<void> onSubmitted(
    String email, AnimationController controller, BuildContext context) async {
  controller.repeat();
  FirebaseAuth _auth = FirebaseAuth.instance;
  try {
    _auth.signInWithEmailAndPassword(email: email, password: "1");
  } on PlatformException catch (e) {
    debugPrint(e.toString());
  } on FirebaseAuthException catch (e) {
    debugPrint(e.toString());
  }
}

这是用于测试的简化形式。无论如何,它甚至没有达到 catch 语句。它在到达 catch 语句之前引发 PlatformException。我不明白。

错误码是这样的。

未处理的异常:[firebase_auth/user-not-found] 没有与此标识符对应的用户记录。该用户可能已被删除。

我明确指定了异常的类型,它应该打印错误消息,但它甚至没有到达 debugPrint() 函数。

我应该如何捕捉异常?

【问题讨论】:

    标签: flutter dart firebase-authentication


    【解决方案1】:

    你做了所有必要的事情吗?

    1. 在 Firebase 控制台中创建 ios/Android 应用
    2. 启用不同的登录方式(谷歌、电子邮件等)
    3. 下载 google-services.json 和 GoogleService-info.plist 并将它们放在相应的文件夹中

    另外,_auth.signInWithEmailAndPassword(email: email, password: "1") 是一个异步过程,需要时间来完成。

    你需要等待

    【讨论】:

    • 是的,我已经完成了 Firebase 控制台上的所有设置,我很遗憾添加“等待”并没有改变任何东西:(
    【解决方案2】:

    根据官方 FlutterFire 文档,您应该存储 `UserCredential` 从变量中的方法“signInWithEmailAndPassword()”对象中检索。所以你的代码应该是这样的:
    try {
      UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
        email: email,
        password: "1"
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user exists with this email.');
      } else if (e.code == 'wrong-password') {
        print('Incorrect Password.');
      }
    }
    

    【讨论】:

    • 它没有任何区别 :( 我的代码仍然无法捕获 PlatformException ......这真的很奇怪我认为try 语句中引发的任何异常都会在以下内容中捕获catch声明...
    • 你能告诉我你用的是什么IDE吗?
    • 这是VSCode,我找到了我自己回答的原因。
    【解决方案3】:

    问题是“他们实际上被抓住了”。

    catch 语句或任何地方都没有问题,但调试器的行为是问题所在。在 Android Studio 上,我可以调整设置,使其在引发异常时不会停止,但在 VSCode 上,无论我做什么,它都会在 catch 语句之前引发异常时停止。

    所以如果我想继续下一行,我只需要在调试工具栏中单击继续即可。

    但我真的希望我也可以更改 VSCode 上的异常中断设置。

    【讨论】:

      【解决方案4】:

      这似乎是在处理异步时如何抛出和捕获错误的问题,FlutterFire 还没有开始将他们的错误放入 try/catch 中 - 我们对此无能为力。

      他们在这里讨论:https://github.com/FirebaseExtended/flutterfire/issues/3475

      这是一个待定的修复:https://github.com/FirebaseExtended/flutterfire/pull/3700

      目前的答案似乎基本上是要么逐步检查异常,要么在调试器中取消选中“未捕获的异常”(这不是很好,因为它不会捕获实际的异常......)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-26
        • 2017-02-05
        • 2012-12-14
        • 2015-11-21
        • 2012-01-10
        相关资源
        最近更新 更多