當用戶在通過 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();
}
}
uj5u.com熱心網友回復:
在您的 try-catch 塊中,您正在捕獲Exception型別,但 Firebase 身份驗證有其自己的例外型別FirebaseAuthException.
有關此特定登錄的可能錯誤代碼,請參見此處,但也有其他錯誤代碼。
檢查以下代碼:
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/385919.html
下一篇:raise真的是一個關鍵詞嗎?
