我已经为我的应用登录了Firebase。我想向用户报告异常,以便他可以正确登录。这是电子邮件地址和密码登录signInWithEmailAndPassword(_email, _password)
。测试我可以创建两个可以自我解释的异常
1 / Error: PlatformException(exception, There is no user record corresponding to this identifier. The user may have been deleted., null)
2 / Error: PlatformException(exception, The password is invalid or the user does not have a password., null)
我正在使用try catch block
来捕获错误。这是我的代码:
void validateAndSubmit() async {
FocusScope.of(context).requestFocus(new FocusNode());
if (validateAndSave()) {
try {
var auth = AuthProvider.of(context).auth;
FirebaseUser user =
await auth.signInWithEmailAndPassword(_email, _password);
print('Signed in: ${user.uid}');
Navigator.pop(context);
widget.loginCallback(user);
} catch (e) {
print('Error: $e');
setState(() {
_showMessage=true;
});
}
}
}
我想根据异常情况给出不同的消息。但是似乎没有与异常相关的任何代码。
答案 0 :(得分:1)
您可以捕获不同种类的异常,对于每种异常,您都可以检查代码
void validateAndSubmit() async {
FocusScope.of(context).requestFocus(new FocusNode());
if (validateAndSave()) {
try {
var auth = AuthProvider.of(context).auth;
FirebaseUser user =
await auth.signInWithEmailAndPassword(_email, _password);
print('Signed in: ${user.uid}');
Navigator.pop(context);
widget.loginCallback(user);
} on FirebaseAuthInvalidUserException catch (e) {
print('FirebaseAuthInvalidUserException: $e');
if (e.code === 'ERROR_USER_NOT_FOUND') {
setState(() {
_showMessage=true;
});
} else {
// do something
}
}
} on FirebaseAuthInvalidCredentialsException catch (e) {
// do something InvalidCredentials
} catch (e) {
// do something else
}
}
答案 1 :(得分:0)
您可以选中e.code
。
签出本地Firebase documentation。它的值类似于“ ERROR_USER_NOT_FOUND”