且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理 Flutter 上的 Firebase 身份验证异常

更新时间:2023-12-05 22:02:28

(21/02/20) 这个答案很旧,其他答案包含跨平台解决方案,所以你应该先看看他们的这是一种后备解决方案.

firebase auth 插件还没有真正的跨平台错误代码系统,所以你必须独立处理 android 和 ios 的错误.

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.

我目前正在使用这个 github 问题的临时修复:#20223

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');
}