Flutter 2.2.2版本PlatformException异常捕获失效及错误提取咨询
关于你的猜测是否正确
该猜测不正确。异常处理失效的核心原因是 Firebase 身份认证相关方法抛出的异常不全是 PlatformException 类型,目前新版 Firebase Auth SDK 抛出的大多是 FirebaseAuthException 类型异常,你仅捕获 PlatformException 时,其他类型的异常未被命中捕获逻辑,就会直接触发程序崩溃,和空安全支持无关。
通用catch(e)提取纯错误消息的方案
你可以在catch块中先做类型判断,分别匹配不同异常类型的消息字段,再统一输出,示例代码如下:
try { final auth = Provider.of<AuthBase>(context, listen: false); if (_formType == EmailSignInFormType.signIn) { await auth.signInWithEmailAndPassword(_email, _password); } else { await auth.createUserWithEmailAndPassword(_email, _password); } Navigator.of(context).pop(); } catch (e) { String errorMsg = "未知登录错误"; if (e is FirebaseAuthException) { errorMsg = e.message ?? errorMsg; } else if (e is PlatformException) { errorMsg = e.message ?? errorMsg; } else { errorMsg = e.toString(); } PlatformAlertDialog( title: 'Sign in failed', content: errorMsg, defaultActionText: 'OK', ).show(context); }
如果要同时兼顾异常捕获完整性和类型安全,也可以叠加多个on捕获分支:
try { // 原有业务逻辑 } on FirebaseAuthException catch (e) { // 处理Firebase认证异常 } on PlatformException catch (e) { // 处理平台异常 } catch (e) { // 兜底处理其他所有异常 }
内容的提问来源于stack exchange,提问作者ahmad zabadnee
相关产品推荐
相关产品推荐

