无法捕获Firebase Auth的'email-already-in-use'错误求助
在使用Firebase Auth实现邮箱注册逻辑时,重复使用同一邮箱注册,预设的Snackbar并未弹出,无法正确捕获'email-already-in-use'错误。
注册逻辑代码
class FirebaseAuthFailure implements IauthFailure { final FirebaseAuth firebaseAuth; final GoogleSignIn googleSignIn; FirebaseAuthFailure(this.firebaseAuth, this.googleSignIn); @override Future<Either<AuthFailure, Unit>> registerWithEmailAndPassword( {required EmailAddress emailAddress, required Password password}) async { final emailAddressStr = emailAddress.value .fold((left) => throw UnexpectedValueError(left), (right) => right); final passwordStr = password.value .fold((left) => throw UnexpectedValueError(left), (right) => right); try { await firebaseAuth.createUserWithEmailAndPassword( email: emailAddressStr, password: passwordStr); return right(unit); } on PlatformException catch (e) { if (e.code == 'email-already-in-use') { return left(const AuthFailure.emailalreadyinuse()); } else { return left(const AuthFailure.servererror()); } } } }
Snackbar相关代码
BlocConsumer<AuthBloc, AuthState>( listener: (context, state) { state.authfailureorsuccess.fold( () {}, (either) => either.fold((failure) { FlushbarHelper.createError( message: failure.map( cancelledbyuser: (_) => 'Cancelled', servererror: (_) => 'Server Error', emailalreadyinuse: (_) => 'Email Already In Use', invalidemailandpasswordcomnination: (_) => 'Invalid Email And Password Combination'), ).show(context); }, (_) {})); }, )
控制台错误信息
I/FirebaseAuth(29404): Creating user with nidhinvninan29@gmail.com with empty reCAPTCHA token
W/System (29404): Ignoring header X-Firebase-Locale because its value was null.
E/RecaptchaCallWrapper(29404): Initial task failed for action RecaptchaAction(action=signUpPassword)with exception - The email address is already in use by another account.
E/flutter (29404): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unhandled error [firebase_auth/email-already-in-use] The email address is already in use by another account. occurred in Instance of 'AuthBloc'.
已尝试的无效方案
- 匹配
e.code == 'email-already-in-use:' - 匹配
e.code == 'firebase_auth/email-already-in-use'
解决方案
问题核心在于异常捕获的类型错误:Firebase Auth当前抛出的是FirebaseAuthException而非PlatformException,原代码的on PlatformException catch (e)无法捕获到目标错误。
修改注册逻辑的异常捕获部分:
try { await firebaseAuth.createUserWithEmailAndPassword( email: emailAddressStr, password: passwordStr); return right(unit); } on FirebaseAuthException catch (e) { // 替换为FirebaseAuthException类型捕获 if (e.code == 'email-already-in-use') { return left(const AuthFailure.emailalreadyinuse()); } else { return left(const AuthFailure.servererror()); } } catch (e) { // 兜底捕获其他未知异常 return left(const AuthFailure.servererror()); }
同时确保已导入Firebase Auth相关包:
import 'package:firebase_auth/firebase_auth.dart';
修改后即可正确捕获email-already-in-use错误,触发对应的Snackbar提示。
内容的提问来源于stack exchange,提问作者nidhin ninan

