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