How to Handle Firebase Auth exceptions on flutter

前端 未结 12 1125
走了就别回头了
走了就别回头了 2020-11-30 07:56

Please does anyone know how to catch firebase Auth exceptions on flutter and display them?

Note: I am not interested in the console (catcherror((e) print(e))

12条回答
  •  不知归路
    2020-11-30 08:29

    I just coded myself a way to do this without Platform dependent Code:

    This is possible since .signInWithEmailAndPassword correctly throws Errors with defined codes, that we can grab to identify the error and handle things in the way the should be handled.

    The following example creates a new Future.error, if any error happens, and a Bloc is then configured to shovel that data through to the Widget.

    Future signIn(String email, String password) async {
      FirebaseUser user;
      String errorMessage;
    
      try {
        AuthResult result = await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
        user = result.user;
      } catch (error) {
        switch (error.code) {
          case "ERROR_INVALID_EMAIL":
            errorMessage = "Your email address appears to be malformed.";
            break;
          case "ERROR_WRONG_PASSWORD":
            errorMessage = "Your password is wrong.";
            break;
          case "ERROR_USER_NOT_FOUND":
            errorMessage = "User with this email doesn't exist.";
            break;
          case "ERROR_USER_DISABLED":
            errorMessage = "User with this email has been disabled.";
            break;
          case "ERROR_TOO_MANY_REQUESTS":
            errorMessage = "Too many requests. Try again later.";
            break;
          case "ERROR_OPERATION_NOT_ALLOWED":
            errorMessage = "Signing in with Email and Password is not enabled.";
            break;
          default:
            errorMessage = "An undefined Error happened.";
        }
      }
    
      if (errorMessage != null) {
        return Future.error(errorMessage);
      }
    
      return user.uid;
    }
    

提交回复
热议问题