【问题标题】:Is there any error in the try-catch exception handling below?下面的try-catch异常处理是否有错误?
【发布时间】:2022-01-19 19:10:52
【问题描述】:

当用户在通过 firebase 身份验证后尝试登录时,我尝试处理异常。但是这个 try-catch 在我的颤振项目中不起作用。

谁能告诉我哪里出错了?我在下面附上了我的代码。

提前谢谢你。

class AuthService {
  //Creating an instance of firebase.
  final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;

  User? _userFromFirebase(auth.User? user) {
    if (user == null) {
      return null;
    }
    return User(user.uid, user.email);
  }

  Stream<User?>? get user {
    return _firebaseAuth.authStateChanges().map(_userFromFirebase);
  }

  Future<User?> signInWithEmailAndPassword(
    String email,
    String password,
  ) async {
    try {
      final credential = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);

      return _userFromFirebase(credential.user);
    } on Exception catch (_, e) {
      //I want to display a toast message if the login fails here. 
      print(e);
    }
  }

  Future<void> signOut() async {
    return await _firebaseAuth.signOut();
  }
}

【问题讨论】:

  • 您能否更具体地说明try catch 不起作用的原因?不应该发生什么?我也认为应该是catch (e, _) 而不是catch (_, e)
  • 我试图处理从 firebase auth 登录过程中可能发生的任何异常。我想要的是尝试使用firebase给出的“signInWithEmailAndPassword”方法进行身份验证。如果发生任何异常,例如密码错误,我想使用 catch 将该消息返回给用户。这就是我想要实现的。顺便说一句,我尝试更改 catch(e, _) 而不是 catch(_, e) 但仍然没有任何区别。谢谢你:)
  • 好的,所以我认为您不能通过这种方法向用户显示任何内容。我建议你在 catch 的最后一行添加一个rethrow,然后在你调用signInWithEmailAndPassword 的地方你可以再次用 try-catch 包围它,然后在 catch 上使用显示一个小吃吧。这有意义吗?

标签: flutter dart exception try-catch


【解决方案1】:

在您的 try-catch 块中,您正在捕获 Exception 类型,但 Firebase 身份验证有其自己的异常类型 FirebaseAuthException

有关此特定登录的可能错误代码,请参阅 here,但也有其他错误代码。

检查以下代码:

try {
  final credential = await _firebaseAuth.signInWithEmailAndPassword(
    email: email, password: password);
  return _userFromFirebase(credential.user);
} on FirebaseAuthException catch (e) {
  // here you will have the different error codes in `e.code`
  // for example `invalid-email` or `wrong-password`
}

如何处理这些错误取决于您。例如,您可以返回错误代码并从调用此函数的位置处理它(如注释中建议的 h8moss)。

请记住,除了FirebaseAuthException 之外,还有其他可能导致登录失败的原因。例如,网络连接可能会关闭。因此,捕获其他错误的更完整的解决方案是:

try {
  // sign in
} on FirebaseAuthException catch (e) {
  // handle Firebase Authentication exceptions
} catch (e) {
  // handle other exceptions
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2011-01-01
    • 2016-09-13
    相关资源
    最近更新 更多