firebase - 如何区分使用 Firebase 进行 flutter 身份验证的异常?

标签 firebase dart flutter firebase-authentication

我有 Firebase 登录我的应用程序。我想向用户报告异常,以便他可以正确登录。在 signInWithEmailAndPassword(_email, _password) 中是电子邮件和密码登录。测试我可以创建两个不言自明的异常

1/Error: PlatformException(exception, 没有该标识对应的用户记录,用户可能已被删除,null)

2/Error: PlatformException(exception, The password is invalid or the user does not have a password., null)

我正在使用 try catch block 来捕获错误。这是我的代码:

void validateAndSubmit() async {
    FocusScope.of(context).requestFocus(new FocusNode());
    if (validateAndSave()) {
      try {
        var auth = AuthProvider.of(context).auth;
        FirebaseUser user =
            await auth.signInWithEmailAndPassword(_email, _password);
        print('Signed in: ${user.uid}');
        Navigator.pop(context);
        widget.loginCallback(user);

      } catch (e) {
        print('Error: $e');
        setState(() {
          _showMessage=true;

        });
      }
    }
  }

我想根据异常给出不同的消息。但是似乎没有任何与异常相关的代码。

最佳答案

你可以捕获不同类型的异常,对于每个异常,你可以检查代码


  void validateAndSubmit() async {
    FocusScope.of(context).requestFocus(new FocusNode());
    if (validateAndSave()) {
      try {
        var auth = AuthProvider.of(context).auth;
        FirebaseUser user =
            await auth.signInWithEmailAndPassword(_email, _password);
        print('Signed in: ${user.uid}');
        Navigator.pop(context);
        widget.loginCallback(user);

      } on FirebaseAuthInvalidUserException catch (e) {
        print('FirebaseAuthInvalidUserException: $e');
        if (e.code === 'ERROR_USER_NOT_FOUND') {
          setState(() {
            _showMessage=true;

          });
        } else {
          // do something
        }
      }
      } on FirebaseAuthInvalidCredentialsException catch (e) {
        // do something InvalidCredentials 
      }  catch (e) {
        // do something else
      } 
    }

关于firebase - 如何区分使用 Firebase 进行 flutter 身份验证的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55050579/

相关文章:

android - Firebase 实时数据库在这种情况下并发请求会发生什么情况?

Flutter Canvas.drawImage() 绘制像素化图像

flutter 错误 : The argument type 'Object?' can't be assigned to the parameter type 'String'

flutter - 如何设计自定义ListWheelScrollView像下面的图像在 flutter ?

ios - UIAlertController 的约束

node.js - 为什么这个可调用的云函数失败并返回 "app":"MISSING"?

java - 如何在 Android 上的 Firebase 中跟踪听众?

dart - 将 Stream<Stream<T>> 转换为 Stream<T>

validation - flutter 下拉菜单,选择在验证错误时被禁用

ios - Flutter - 运行 pod install 出现问题 - `image_picker_modern`