Java 如何捕获 Firebase Auth 特定的异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37859582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch a Firebase Auth specific exceptions
提问by Relm
Using Firebase, how do I catch a specific exception and tell the user gracefully about it? E.g :
使用 Firebase,我如何捕获特定异常并优雅地告诉用户它?例如:
FirebaseAuthInvalidCredentialsException: The email address is badly formatted.
FirebaseAuthInvalidCredentialsException:电子邮件地址格式错误。
I'm using the code below to signup the user using email and password, but I'm not that advanced in java.
我正在使用下面的代码使用电子邮件和密码注册用户,但我在 Java 方面并不那么先进。
mAuth.createUserWithEmailAndPassword(email, pwd)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
//H.toast(c, task.getException().getMessage());
Log.e("Signup Error", "onCancelled", task.getException());
} else {
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getUid();
}
}
});
采纳答案by Steve Guidetti
You can throw the Exception returned by task.getException
inside a try block and catch each type of Exception that may be thrown by the method you are using.
您可以抛出task.getException
try 块内返回的异常,并捕获您正在使用的方法可能抛出的每种类型的异常。
Here is an example from the OnCompleteListener
for the createUserWithEmailAndPassword
method.
下面是OnCompleteListener
forcreateUserWithEmailAndPassword
方法的一个例子。
if(!task.isSuccessful()) {
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
mTxtPassword.setError(getString(R.string.error_weak_password));
mTxtPassword.requestFocus();
} catch(FirebaseAuthInvalidCredentialsException e) {
mTxtEmail.setError(getString(R.string.error_invalid_email));
mTxtEmail.requestFocus();
} catch(FirebaseAuthUserCollisionException e) {
mTxtEmail.setError(getString(R.string.error_user_exists));
mTxtEmail.requestFocus();
} catch(Exception e) {
Log.e(TAG, e.getMessage());
}
}
回答by pdegand59
You should use ((FirebaseAuthException)task.getException()).getErrorCode()
to get the type of error and fail gracefully if this is the error code for a bad formatted email.
((FirebaseAuthException)task.getException()).getErrorCode()
如果这是错误格式的电子邮件的错误代码,您应该使用获取错误类型并正常失败。
Unfortunately, I couldn't find the list of error codes used by Firebase. Trigger the exception once, note the error code and code accordingly.
不幸的是,我找不到 Firebase 使用的错误代码列表。触发一次异常,记下错误代码和相应的代码。
回答by Anmol Bhardwaj
If you are sending upstream messages from user to cloud, implement firebase callback functions onMessageSent
and onSendError
to check the status of upstream messages. In error cases, onSendError
returns a SendExceptionwith an error code.
如果您要从用户向云端发送上游消息,请实现 firebase 回调函数onMessageSent
并onSendError
检查上游消息的状态。在错误情况下,onSendError
返回带有错误代码的SendException。
For example, if the client attempts to send more messages after the 20-message limit is reached, it returns SendException#ERROR_TOO_MANY_MESSAGES.
例如,如果客户端在达到 20 条消息限制后尝试发送更多消息,则返回SendException#ERROR_TOO_MANY_MESSAGES。
回答by kingspeech
In addition to @pdegand59 answer, I found some error code in Firebase library and test on Android (the returned error code). Hope this helps, Regards.
除了@pdegand59 的回答,我在 Firebase 库中发现了一些错误代码并在 Android 上测试(返回的错误代码)。希望这会有所帮助,问候。
("ERROR_INVALID_CUSTOM_TOKEN", "The custom token format is incorrect. Please check the documentation."));
("ERROR_CUSTOM_TOKEN_MISMATCH", "The custom token corresponds to a different audience."));
("ERROR_INVALID_CREDENTIAL", "The supplied auth credential is malformed or has expired."));
("ERROR_INVALID_EMAIL", "The email address is badly formatted."));
("ERROR_WRONG_PASSWORD", "The password is invalid or the user does not have a password."));
("ERROR_USER_MISMATCH", "The supplied credentials do not correspond to the previously signed in user."));
("ERROR_REQUIRES_RECENT_LOGIN", "This operation is sensitive and requires recent authentication. Log in again before retrying this request."));
("ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL", "An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address."));
("ERROR_EMAIL_ALREADY_IN_USE", "The email address is already in use by another account."));
("ERROR_CREDENTIAL_ALREADY_IN_USE", "This credential is already associated with a different user account."));
("ERROR_USER_DISABLED", "The user account has been disabled by an administrator."));
("ERROR_USER_TOKEN_EXPIRED", "The user\'s credential is no longer valid. The user must sign in again."));
("ERROR_USER_NOT_FOUND", "There is no user record corresponding to this identifier. The user may have been deleted."));
("ERROR_INVALID_USER_TOKEN", "The user\'s credential is no longer valid. The user must sign in again."));
("ERROR_OPERATION_NOT_ALLOWED", "This operation is not allowed. You must enable this service in the console."));
("ERROR_WEAK_PASSWORD", "The given password is invalid."));
回答by Itzdsp
You can use either steve-guidetti or pdegand59 method. I used steve-guidetti's method(Two exceptions are missing)
您可以使用 steve-guidetti 或 pdegand59 方法。我使用了 steve-guidetti 的方法(缺少两个例外)
For all possible exception please find below ref.
对于所有可能的例外,请在下面找到参考。
It is well documented here.
它在这里有很好的记录。
https://firebase.google.com/docs/reference/js/firebase.auth.Auth
https://firebase.google.com/docs/reference/js/firebase.auth.Auth
Search for "createUserWithEmailAndPassword" and find the
搜索“createUserWithEmailAndPassword”并找到
Error Codes
auth/email-already-in-use
错误代码
身份验证/电子邮件已在使用中
Thrown if there already exists an account with the given email address.
auth/invalid-email
身份验证/无效电子邮件
Thrown if the email address is not valid.
auth/operation-not-allowed
授权/操作不允许
Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.
auth/weak-password
身份验证/弱密码
Thrown if the password is not strong enough.
For all five exceptions: Check here
对于所有五个例外:检查这里
https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthException
https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthException
Here you can find 5 different types of AuthException. 4 Known Direct subclass and 1 indirect subclass
在这里您可以找到 5 种不同类型的 AuthException。4 个已知的直接子类和 1 个间接子类
You can use either steve-guidetti or pdegand59 method.
您可以使用 steve-guidetti 或 pdegand59 方法。
回答by RedLEON
I tried another solutions but didn't like them.
我尝试了另一种解决方案,但不喜欢它们。
What about this:
那这个呢:
if (!task.isSuccessful()) {
Exception exc = task.getException();
if (exc.getMessage().contains("The email address is badly formatted.")) {
etUser.setError(getString(R.string.error_wrong_email));
etUser.requestFocus();
}
else
if (exc.getMessage().contains("There is no user record corresponding to this identifier. The user may have been deleted.")) {
etUser.setError(getString(R.string.error_user_not_exist));
etUser.requestFocus();
}
else
if (exc.getMessage().contains("The password is invalid or the user does not have a password")) {
etPass.setError(getString(R.string.error_wrong_password));
etPass.requestFocus();
}
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(AuthActivity.this, R.string.auth_failed,
Toast.LENGTH_SHORT).show();
}
回答by Steven Berdak
If you simply want display a message to the user this works. Simple and Elegant:
如果您只是想向用户显示一条消息,这很有效。简单而优雅:
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(LoginActivity.this, "User Authentication Failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
It appears that the .getMessage() method converts the exception to a usable format for us already and all we have to do is display that somewhere to the user.
似乎 .getMessage() 方法已经将异常转换为我们可用的格式,我们所要做的就是将其显示给用户。
(This is my first comment, constructive criticism please)
(这是我的第一条评论,请建设性批评)
回答by NickUnuchek
try {
throw task.getException();
} catch(FirebaseAuthException e) {
switch (e.getErrorCode()){
case "ERROR_WEAK_PASSWORD":
Toast.makeText(this, "The given password is invalid.", Toast.LENGTH_SHORT).show();
break;
//and other
}
}
error codes: https://stackoverflow.com/a/38244409/2425851
回答by Ra Isse
To catch a firebase Exception is easy, you should add .addOnFailureListener
after you add .addOnCompleteListener
like this:
要捕获 firebase 异常很容易,您应该在添加.addOnFailureListener
后添加.addOnCompleteListener
如下内容:
private void login_user(String email, String password) {
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}if(!task.isSuccessful()){
// To know The Excepton
//Toast.makeText(LoginActivity.this, ""+task.getException(), Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if( e instanceof FirebaseAuthInvalidUserException){
Toast.makeText(LoginActivity.this, "This User Not Found , Create A New Account", Toast.LENGTH_SHORT).show();
}
if( e instanceof FirebaseAuthInvalidCredentialsException){
Toast.makeText(LoginActivity.this, "The Password Is Invalid, Please Try Valid Password", Toast.LENGTH_SHORT).show();
}
if(e instanceof FirebaseNetworkException){
Toast.makeText(LoginActivity.this, "Please Check Your Connection", Toast.LENGTH_SHORT).show();
}
}
});
回答by Diego Venancio
LOGIN_EXCEPTIONS
LOGIN_EXCEPTIONS
FirebaseAuthException
- Generic exception related to Firebase Authentication. Check the error code and message for more details.
FirebaseAuthException
- 与 Firebase 身份验证相关的通用异常。查看错误代码和消息以了解更多详细信息。
ERROR_USER_DISABLE
D if the user has been disabled (for example, in the Firebase console)
ERROR_USER_DISABLE
D 如果用户已被禁用(例如,在 Firebase 控制台中)
ERROR_USER_NOT_FOUND
if the user has been deleted (for example, in the Firebase console, or in another instance of this app)
ERROR_USER_NOT_FOUND
如果用户已被删除(例如,在 Firebase 控制台中,或在此应用的另一个实例中)
ERROR_USER_TOKEN_EXPIRED
if the user's token has been revoked in the backend. This happens automatically if the user's credentials change in another device (for example, on a password change event).
ERROR_USER_TOKEN_EXPIRED
如果用户的令牌已在后端被撤销。如果用户的凭据在另一台设备中发生更改(例如,密码更改事件),则会自动发生这种情况。
ERROR_INVALID_USER_TOKEN
if the user's token is malformed. This should not happen under normal circumstances.
ERROR_INVALID_USER_TOKEN
如果用户的令牌格式错误。这在正常情况下不应该发生。
mAuth.signInWithEmailAndPassword(login, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
}else if (task.getException() instanceof FirebaseAuthInvalidUserException) {
}else if(((FirebaseAuthException) task.getException()).getErrorCode().equals("ERROR_USER_DISABLED"))
{
}else if(((FirebaseAuthException) task.getException()).getErrorCode().equals("ERROR_USER_NOT_FOUND "))
{
}else if(((FirebaseAuthException) task.getException()).getErrorCode().equals("ERROR_USER_TOKEN_EXPIRED "))
{
}else if(((FirebaseAuthException) task.getException()).getErrorCode().equals("ERROR_INVALID_USER_TOKEN "))
{
}
}
});
REGISTER_EXCEPTIONS
REGISTER_EXCEPTIONS
FirebaseAuthEmailException
Represents the exception which is a result of an attempt to send an email via Firebase Auth (e.g. a password reset email)
表示由于尝试通过 Firebase 身份验证发送电子邮件(例如密码重置电子邮件)而导致的异常
FirebaseAuthInvalidCredentialsException
- Thrown when one or more of the credentials passed to a method fail to identify and/or authenticate the user subject of that operation. Inspect the error code and message to find out the specific cause.
FirebaseAuthInvalidCredentialsException
- 当传递给方法的一个或多个凭据无法识别和/或验证该操作的用户主体时抛出。检查错误代码和消息以找出具体原因。
FirebaseAuthWeakPasswordException
- Thrown when using a weak password (less than 6 chars) to create a new account or to update an existing account's password. Use getReason() to get a message with the reason the validation failed that you can display to your users.
FirebaseAuthWeakPasswordException
- 使用弱密码(少于 6 个字符)创建新帐户或更新现有帐户的密码时抛出。使用 getReason() 获取一条消息,说明验证失败的原因,您可以向用户显示该消息。