Flutter - 尝试捕捉不处理 firebase_auth 错误

时间:2021-01-09 15:08:12

标签: firebase flutter dart firebase-authentication

我在处理 firebase_auth 错误时遇到问题,每次尝试登录时,我都会遇到一些错误, 虽然我使用过尝试和捕获。 早些时候我在 vsc 中关闭了未捕获的异常选项,但我也想从 catch 中获取错误消息

sample errors message

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()}'));
  }
}

2 个答案:

答案 0 :(得分:0)

此代码仅捕获所编写的 PlatformException。

  try {
    await _auth.signInWithEmailAndPassword(email: email, password: password);
  } on PlatformException catch (e) {
    return Left(LoginFailure(errorMessage: '${e.toString()}'));
  }

您可以像这样捕获所有异常。

  try {
    await _auth.signInWithEmailAndPassword(email: email, password: password);
  } catch (e) {
    return Left(LoginFailure(errorMessage: '${e.toString()}'));
  }

你也可以这样做

  try {
    await _auth.signInWithEmailAndPassword(email: email, password: password);
  } on PlatformException catch (e) {
    return Left(LoginFailure(errorMessage: '${e.toString()}'));
  } catch(e) {
    // All other than Platform exception will drop here 
    print(e);
  }

答案 1 :(得分:0)

在您的日志中,您看到未捕获异常的类型是 PlatformException,但它不是 signInWithEmailAndPassword() 抛出的原始异常的类型;当它拦截异常1时,它被flutter框架用来包装它。因此,如果您只想捕获 signInWithEmailAndPassword() 抛出的异常,请首先检查它们的确切类型,查阅文档(如果明确)或使用不带 on 子句的 try/catch,如下所示:< /p>

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 有自己的异常捕获机制,因此并非真正“未捕获”;参见例如这个 doc on error in flutter)