firebase - Flutter - 尝试捕获不处理 firebase_auth 错误
问题描述
我在处理 firebase_auth 错误时遇到问题,每次尝试登录时,都会遇到一些错误,尽管我使用了 try 和 catch。早些时候我关闭了 vsc 中的未捕获异常选项,但我也想从 catch 中获取错误消息
Future<Either<LoginFailure, LoginSucces>> signInWithEmail(
{String email, String password}) async {
try {
await _auth.signInWithEmailAndPassword(email: email, password: password);
} on PlatformException catch (e) {
return Left(LoginFailure(errorMessage: '${e.toString()}'));
}
}
解决方案
在您的日志中,您看到未捕获异常的类型是PlatformException
,但它不是由signInWithEmailAndPassword()
;引发的原始异常的类型。当它拦截异常1时,flutter 框架会使用它来包装它。因此,如果您只想捕获由 抛出的异常signInWithEmailAndPassword()
,请首先检查它们的确切类型,查阅文档(如果它是明确的)或使用不带on
子句的 try/catch,如下所示:
try {
await _auth.signInWithEmailAndPassword(email: email, password: password);
} catch (e, stack) {
print("Catched exception: $e");
//if the exception log not shows the type (it is rare), you can log the exact type with:
print(e.runtimeType);
}
当您知道要捕获的异常的正确类型时,您可以使用以下on
子句:
try {
await _auth.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseError catch (e, stack) {
print(e);
//exceptions with a type other than FirebaseError are not caught here
}
注意FirebaseError
是使用我的包抛出的类型,firebase
(其他也存在,比如firebase_auth
);如果您使用不同的包,请自行检查您需要捕获哪些异常。
1 Flutter 有自己的异常捕获机制,因此并不是真正的“未捕获”;例如,请参阅this doc on error in flutter)
推荐阅读
- excel - 在 VBA 中提高 For Loop 和 With 语句的速度
- javascript - add 不是函数
- python-3.x - 为什么它不转一圈?以及如何解决?
- css - 使用css将左右元素放在同一行
- javascript - ChartJS - 当我从 API 获取数据以获取新数据时更新不起作用
- java - 检索实例的 ID,就像 Eclipse 的调试器一样
- javascript - 如果将 OnChange() 作为 prop 传递,它可以在 ReactJs 上的父组件中接收多个函数吗?
- csv - 来自 CSV 文件的乳胶表
- typescript - 使用异步存储进行本地化
- r - 尝试在 R 中安装 quickdraw 包