How to Handle Firebase Auth exceptions on flutter

前端 未结 12 1126
走了就别回头了
走了就别回头了 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:27

    I prefer to create api layer response and error models and wrap the firebase plugin error and response objects in them. For sign in with email and password i have this

    @override
      Future loginWithEmailAndPassword(String email, String password) async {
        try {
          await _firebaseAuth.signInWithEmailAndPassword(
              email: email, password: password);
          return FirebaseSignInWithEmailResponse();
        } catch (exception) {
          return _mapLoginWithEmailError(exception);
        }
      }
    
      ApiError _mapLoginWithEmailError(PlatformException error) {
        final code = error.code;
        if (code == 'ERROR_INVALID_EMAIL') {
          return FirebaseSignInWithEmailError(
              message: 'Your email is not valid. Please enter a valid email',
              type: FirebaseSignInWithEmailErrorType.INVALID_EMAIL);
        } else if (code == 'ERROR_WRONG_PASSWORD') {
          return FirebaseSignInWithEmailError(
              message: 'Your password is incorrect',
              type: FirebaseSignInWithEmailErrorType.WRONG_PASSWORD);
        } else if (code == 'ERROR_USER_NOT_FOUND') {
          return FirebaseSignInWithEmailError(
              message: 'You do not have an account. Please Sign Up to'
                  'proceed',
              type: FirebaseSignInWithEmailErrorType.USER_NOT_FOUND);
        } else if (code == 'ERROR_TOO_MANY_REQUESTS') {
          return FirebaseSignInWithEmailError(
              message: 'Did you forget your credentials? Reset your password',
              type: FirebaseSignInWithEmailErrorType.TOO_MANY_REQUESTS);
        } else if (code == 'ERROR_USER_DISABLED') {
          return FirebaseSignInWithEmailError(
              message: 'Your account has been disabled. Please contact support',
              type: FirebaseSignInWithEmailErrorType.USER_DISABLED);
        } else if (code == 'ERROR_OPERATION_NOT_ALLOWED') {
          throw 'Email and Password accounts are disabled. Enable them in the '
              'firebase console?';
        } else {
          return FirebaseSignInWithEmailError(
              message: 'Make sure you have a stable connection and try again'
              type: FirebaseSignInWithEmailErrorType.CONNECTIVITY);
        }
      }
    

    I never return the AuthResult from firebase. Instead i listen to the onAuthStateChanged stream and react accordingly if there is a change.

提交回复
热议问题