How to Handle Firebase Auth exceptions on flutter

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

    (21/02/20) EDIT: This answer is old and the other answers contains cross platform solutions so you should look at theirs first and treat this as a fallback solution.

    The firebase auth plugin doesn't really have a proper cross-platform error code system yet so you have to handle errors for android and ios independently.

    I'm currently using the temporary fix from this github issue: #20223

    Do note since its a temp fix, don't expect it to be fully reliable as a permanent solution.

    enum authProblems { UserNotFound, PasswordNotValid, NetworkError }
    
    try {
      FirebaseUser user = await FirebaseAuth.instance.signInWithEmailAndPassword(
          email: email,
          password: password,
      );
    } catch (e) {
      authProblems errorType;
      if (Platform.isAndroid) {
        switch (e.message) {
          case 'There is no user record corresponding to this identifier. The user may have been deleted.':
            errorType = authProblems.UserNotFound;
            break;
          case 'The password is invalid or the user does not have a password.':
            errorType = authProblems.PasswordNotValid;
            break;
          case 'A network error (such as timeout, interrupted connection or unreachable host) has occurred.':
            errorType = authProblems.NetworkError;
            break;
          // ...
          default:
            print('Case ${e.message} is not yet implemented');
        }
      } else if (Platform.isIOS) {
        switch (e.code) {
          case 'Error 17011':
            errorType = authProblems.UserNotFound;
            break;
          case 'Error 17009':
            errorType = authProblems.PasswordNotValid;
            break;
          case 'Error 17020':
            errorType = authProblems.NetworkError;
            break;
          // ...
          default:
            print('Case ${e.message} is not yet implemented');
        }
      }
      print('The error is $errorType');
    }
    

提交回复
热议问题