Flutter中无法捕获FirebaseAuthException的问题及解决
FirebaseAuthException无法捕获的问题排查与解决
问题场景
尝试通过try-catch捕获Firebase登录时的FirebaseAuthException,但始终失败,控制台抛出未处理的异常。
错误代码
TextButton( onPressed: () async { try { final email = _email.text; final password = _password.text; final userCredential = FirebaseAuth.instance.signInWithEmailAndPassword( email: email, password: password, ); print(userCredential); } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { print(e.message); } } }, child: Text("Login"), ),
控制台输出
I/FirebaseAuth( 2241): Logging in as asdasdhas@gmail.com with empty reCAPTCHA token E/RecaptchaCallWrapper( 2241): Initial task failed for action RecaptchaAction(action=custom_signInWithPassword)with exception - There is no user record corresponding to this identifier. The user may have been deleted. E/flutter ( 2241): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.
问题原因
signInWithEmailAndPassword是异步方法,调用时未添加await关键字,导致代码直接返回Future<UserCredential>对象,不会等待异步操作完成并捕获其抛出的异常,异常最终以未处理的Future异常形式抛出。
修复方案
在调用signInWithEmailAndPassword时添加await关键字,确保异步操作完成后再执行后续代码,此时异常会被正确捕获到try-catch块中:
TextButton( onPressed: () async { try { final email = _email.text; final password = _password.text; final userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword( email: email, password: password, ); print(userCredential); } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { print(e.message); } } }, child: Text("Login"), ),
内容的提问来源于stack exchange,提问作者Alin Ahmet Tekin
相关产品推荐
相关产品推荐

