Firebase Auth中reauthenticateWithCredential无法捕获wrong-password异常
Firebase Auth reauthenticateWithCredential 异常捕获失败解决方案
你遇到的问题是调用reauthenticateWithCredential()时无法捕获FirebaseAuthException(比如wrong-password错误直接抛出未处理异常),但signInWithEmailAndPassword()能正常捕获同类异常。
错误代码示例
AuthCredential credential = EmailAuthProvider.credential( email: auth.currentUser!.email.toString(), password: password.toString()); UserCredential userCredential = await auth.currentUser!.reauthenticateWithCredential(credential); on FirebaseAuthException catch (e) { if (e.code == "wrong-password") { print("Wrong password");}
未处理异常日志
E/flutter (11690): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_auth/wrong-password] The password is invalid or the user does not have a password.
对比正常工作的登录代码
void login(String email, String password) async { try { await auth.signInWithEmailAndPassword(email: email, password: password); Get.offAllNamed(Routes.HOME); } on FirebaseAuthException catch (e) { if (e.code == "wrong-password") { print("Wrong password");}
问题原因
异常捕获必须依赖完整的try/catch结构,你当前的reauthenticateWithCredential()调用没有被try块包裹,直接使用on catch不符合Dart的异常捕获语法,导致异常无法被拦截。而登录函数中正确用try包裹了异步调用,所以能正常捕获异常。
修正后的代码
void reauthenticate(String password) async { try { AuthCredential credential = EmailAuthProvider.credential( email: auth.currentUser!.email.toString(), password: password.toString() ); UserCredential userCredential = await auth.currentUser!.reauthenticateWithCredential(credential); // 重新认证成功后的业务逻辑 } on FirebaseAuthException catch (e) { if (e.code == "wrong-password") { print("Wrong password"); } // 可添加其他Firebase认证错误的处理逻辑,比如user-not-found等 } catch (e) { // 捕获非FirebaseAuth类型的异常 print("其他异常:${e.toString()}"); } }
关键注意点
- 所有可能抛出异常的异步操作必须放在
try代码块内 - 使用
on FirebaseAuthException catch专门捕获Firebase认证相关异常,精准处理不同错误码 - 额外的
catch块可以处理其他意外异常,避免程序崩溃
内容的提问来源于stack exchange,提问作者adanimustafid
相关产品推荐
相关产品推荐

