Firebase Auth异常处理问题:无法捕获PlatformException(ERROR-WRONG-PASSWORD)
Firebase Auth异常捕获问题解决
核心问题分析
新版本firebase_auth的异常类型变化:在
firebase_auth: ^4.7.0中,所有认证相关操作(比如signInWithEmailAndPassword)抛出的异常都是FirebaseAuthException,不再直接抛出PlatformException。你看到的ERROR-WRONG-PASSWORD是旧版本的错误码格式,新版本对应的是小写的wrong-password——也就是你已经在FirebaseAuthException分支里处理的情况。未捕获的数据库操作异常:你代码中
FirebaseDatabase的once()调用放在了then()回调里,不在login方法的try块范围内,这部分操作如果抛出PlatformException,会无法被当前的catch分支捕获。
修复后的代码
Future<void> login(String email, String password) async { try { final credential = await FirebaseAuth.instance .signInWithEmailAndPassword(email: email, password: password); if (credential != null) { emit(state.copyWith(user: credential.user)); DatabaseReference userRef = FirebaseDatabase.instance .ref() .child('users/${credential.user?.uid}'); // 改用await,让数据库操作也处于try块的捕获范围内 final event = await userRef.once(); final dataSnapShot = event.snapshot; if (dataSnapShot.value != null) { emit(state.copyWith( loadingState: PageLoadingState.submitSuccessEvent)); } } } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { emit( state.copyWith( loadingState: PageLoadingState.submitErrorEvent, errorMessage: '未找到匹配的用户信息。'), ); } else if (e.code == 'wrong-password') { emit( state.copyWith( loadingState: PageLoadingState.submitErrorEvent, errorMessage: '邮箱或密码错误。'), ); } } on PlatformException catch (e) { // 现在这个分支只会捕获数据库操作等其他平台相关异常 if (e.code == 'ERROR_WRONG_PASSWORD' || e.code == 'wrong-password') { emit( state.copyWith( loadingState: PageLoadingState.submitErrorEvent, errorMessage: '邮箱或密码错误。'), ); } else if (e.code == 'ERROR_USER_NOT_FOUND' || e.code == 'user-not-found') { emit( state.copyWith( loadingState: PageLoadingState.submitErrorEvent, errorMessage: '未找到用户。'), ); } else { emit( state.copyWith( loadingState: PageLoadingState.submitErrorEvent, errorMessage: '数据库操作出错,请稍后重试。'), ); } } catch (e) { emit( state.copyWith( loadingState: PageLoadingState.submitErrorEvent, errorMessage: '登录过程中发生错误,请稍后重试。'), ); } }
关键修改点
- 将
userRef.once().then(...)改为await userRef.once(),让数据库操作也纳入try块的异常捕获范围。 - 保留
PlatformException捕获分支,但调整错误码判断,兼容新旧格式,同时处理数据库操作可能抛出的平台异常。 - 确认
FirebaseAuthException的错误码使用新版本的小写格式(如wrong-password),这是当前版本firebase_auth抛出的正确错误码。
内容的提问来源于stack exchange,提问作者Convert.ToInt32
相关产品推荐
相关产品推荐

