首页 > 解决方案 > 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()}'));
  }
}

标签: firebaseflutterdartfirebase-authentication

解决方案


在您的日志中,您看到未捕获异常的类型是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


推荐阅读