如何捕获 Firebase Auth 特定异常

Posted

技术标签:

【中文标题】如何捕获 Firebase Auth 特定异常【英文标题】:How to catch a Firebase Auth specific exceptions 【发布时间】:2016-10-17 23:51:16 【问题描述】:

使用 Firebase,我如何捕获特定异常并优雅地告知用户?例如:

FirebaseAuthInvalidCredentialsException:电子邮件地址错误 格式化。

我正在使用下面的代码使用电子邮件和密码注册用户,但我在 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();
        
        
);

【问题讨论】:

【参考方案1】:

您可以在 try 块中抛出 task.getException 返回的异常,并捕获您正在使用的方法可能抛出的每种类型的异常。

这是来自OnCompleteListenercreateUserWithEmailAndPassword 方法的示例。

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());
    

【讨论】:

我对此有疑问。 Firebase 只是返回给我一个 FirebaseException,而不是 FirebaseAuthWeakPasswordException 或其他。但消息似乎很好:“WEAK_PASSWORD”。有什么想法吗? 您可以检查最后一个 catch 块中的消息以查找任何不具有特定类型的异常。 是的,我明白了。但是为什么你有 FirebaseAuthWeakPasswordException 而我没有呢?如果我用 msg 类型做一个 switch 案例,而我应该能够用类类型正确地做到这一点,这是糟糕的代码。 我发现 Firebase 框架在其抛出的异常类型方面不一致。因此,我不得不以某些方法检查消息。它更混乱,但你必须使用你得到的东西。我确实提交了错误报告,但我认为没有任何结果。【参考方案2】:

除了@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."));
 ("ERROR_MISSING_EMAIL", "An email address must be provided.";

【讨论】:

【参考方案3】:

有许多与 firebase 身份验证相关的例外情况。 除了@kingspeech

您应该使用((FirebaseAuthException)task.getException()).getErrorCode() 获取错误类型,然后在switch 中处理它,如下所示:

private void loginUser(String email, String password) 

        mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() 

            @Override
            public void onComplete(@NonNull Task<AuthResult> task) 

                if (task.isSuccessful()) 

                    startActivity(new Intent(MainActivity.this, Main2Activity.class));

                 else 

                    String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();

                    switch (errorCode) 

                        case "ERROR_INVALID_CUSTOM_TOKEN":
                            Toast.makeText(MainActivity.this, "The custom token format is incorrect. Please check the documentation.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_CUSTOM_TOKEN_MISMATCH":
                            Toast.makeText(MainActivity.this, "The custom token corresponds to a different audience.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_INVALID_CREDENTIAL":
                            Toast.makeText(MainActivity.this, "The supplied auth credential is malformed or has expired.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_INVALID_EMAIL":
                            Toast.makeText(MainActivity.this, "The email address is badly formatted.", Toast.LENGTH_LONG).show();
                            etEmail.setError("The email address is badly formatted.");
                            etEmail.requestFocus();
                            break;

                        case "ERROR_WRONG_PASSWORD":
                            Toast.makeText(MainActivity.this, "The password is invalid or the user does not have a password.", Toast.LENGTH_LONG).show();
                            etPassword.setError("password is incorrect ");
                            etPassword.requestFocus();
                            etPassword.setText("");
                            break;

                        case "ERROR_USER_MISMATCH":
                            Toast.makeText(MainActivity.this, "The supplied credentials do not correspond to the previously signed in user.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_REQUIRES_RECENT_LOGIN":
                            Toast.makeText(MainActivity.this, "This operation is sensitive and requires recent authentication. Log in again before retrying this request.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL":
                            Toast.makeText(MainActivity.this, "An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_EMAIL_ALREADY_IN_USE":
                            Toast.makeText(MainActivity.this, "The email address is already in use by another account.   ", Toast.LENGTH_LONG).show();
                            etEmail.setError("The email address is already in use by another account.");
                            etEmail.requestFocus();
                            break;

                        case "ERROR_CREDENTIAL_ALREADY_IN_USE":
                            Toast.makeText(MainActivity.this, "This credential is already associated with a different user account.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_USER_DISABLED":
                            Toast.makeText(MainActivity.this, "The user account has been disabled by an administrator.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_USER_TOKEN_EXPIRED":
                            Toast.makeText(MainActivity.this, "The user\\'s credential is no longer valid. The user must sign in again.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_USER_NOT_FOUND":
                            Toast.makeText(MainActivity.this, "There is no user record corresponding to this identifier. The user may have been deleted.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_INVALID_USER_TOKEN":
                            Toast.makeText(MainActivity.this, "The user\\'s credential is no longer valid. The user must sign in again.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_OPERATION_NOT_ALLOWED":
                            Toast.makeText(MainActivity.this, "This operation is not allowed. You must enable this service in the console.", Toast.LENGTH_LONG).show();
                            break;

                        case "ERROR_WEAK_PASSWORD":
                            Toast.makeText(MainActivity.this, "The given password is invalid.", Toast.LENGTH_LONG).show();
                            etPassword.setError("The password is invalid it must 6 characters at least");
                            etPassword.requestFocus();
                            break;

                    
                
            
        );
    

【讨论】:

【参考方案4】:

您应该使用((FirebaseAuthException)task.getException()).getErrorCode() 来获取错误类型,如果这是格式错误的电子邮件的错误代码,则正常失败。

很遗憾,我找不到 Firebase 使用的错误代码列表。 触发一次异常,记下相应的错误码和代码。

【讨论】:

task.getException() 不能始终转换为 FirebaseAuthException,例如在没有网络连接的情况下。在这种情况下,异常是 FirebaseNetworkException @DavidH 如果你使用 task.getException() 不为空,它会解决这个问题 @mehmet 不,它不会解决问题,因为 task.getException() 在 FirebaseNetworkException 时不为空【参考方案5】:

如果您只是想向用户显示一条消息,这是可行的。简洁优雅:

if (!task.isSuccessful()) 
    Log.w(TAG, "signInWithEmail:failed", task.getException());
    Toast.makeText(LoginActivity.this, "User Authentication Failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();

.getMessage() 方法似乎已经将异常转换为对我们可用的格式,我们所要做的就是将其显示给用户。

(这是我的第一条评论,请有建设性的批评)

【讨论】:

这会在getMessage() 方法中给出警告:Method invocation 'getMessage' may produce 'java.lang.NullPointerException'。如何解决这个问题? 它告诉你 getException() 可以返回 null 所以你可以添加... if(task.getException != null) Toast.makeText... ;【参考方案6】:

您可以使用 steve-guidetti 或 pdegand59 方法。我用的是steve-guidetti的方法(少了两个例外)

对于所有可能的例外情况,请在下面找到参考。

这里有很好的记录。

https://firebase.google.com/docs/reference/js/firebase.auth.Auth

搜索“createUserWithEmailAndPassword”并找到

错误代码

身份验证/电子邮件已在使用中

Thrown if there already exists an account with the given email address. 

身份验证/无效电子邮件

Thrown if the email address is not valid.

授权/不允许操作

Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.

身份验证/弱密码

Thrown if the password is not strong enough. 

对于所有五个例外:检查这里

https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthException

在这里您可以找到 5 种不同类型的 AuthException。 4 个已知的直接子类和 1 个间接子类

您可以使用 steve-guidetti 或 pdegand59 方法。

【讨论】:

这实际上并没有回答他的问题。 这是针对特定于 Auth 的权限,缺少另外两个例外。检查参考 他问的是“我如何捕获一个特定的异常并优雅地告诉用户”而不是“给我一个可能的异常列表”。您的回答对这两件事都没有帮助——如何捕获异常,或者如何通知用户。【参考方案7】:

使用 Kotlin 的解决方案

 fun signInWithEmail(email: String, passKey: String) 
    FirebaseAuth.getInstance().signInWithEmailAndPassword(email, passKey).addOnSuccessListener 
        it.user?.let 
            authResultOperation.postValue(AuthResultOperation.OnSuccessSignIn)
        
    .addOnFailureListener 
        val errorCode = (it.exception as FirebaseAuthException).errorCode
        val errorMessage = authErrors[errorCode] ?: R.string.error_login_default_error
        Toast.makeText(context, context.getString(errorMessage),Toast.LENGTH_LONG).show()
    

说明:基本上它只是一个将firebase错误代码与自定义字符串资源匹配的地图。

val authErrors = mapOf("ERROR_INVALID_CUSTOM_TOKEN" to R.string.error_login_custom_token,
        "ERROR_CUSTOM_TOKEN_MISMATCH" to R.string.error_login_custom_token_mismatch,
        "ERROR_INVALID_CREDENTIAL" to R.string.error_login_credential_malformed_or_expired,
        "ERROR_INVALID_EMAIL" to R.string.error_login_invalid_email,
        "ERROR_WRONG_PASSWORD" to R.string.error_login_wrong_password,
        "ERROR_USER_MISMATCH" to R.string.error_login_user_mismatch,
        "ERROR_REQUIRES_RECENT_LOGIN" to R.string.error_login_requires_recent_login,
        "ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL" to R.string.error_login_accounts_exits_with_different_credential,
        "ERROR_EMAIL_ALREADY_IN_USE" to  R.string.error_login_email_already_in_use,
        "ERROR_CREDENTIAL_ALREADY_IN_USE" to R.string.error_login_credential_already_in_use,
        "ERROR_USER_DISABLED" to R.string.error_login_user_disabled,
        "ERROR_USER_TOKEN_EXPIRED" to R.string.error_login_user_token_expired,
        "ERROR_USER_NOT_FOUND" to R.string.error_login_user_not_found,
        "ERROR_INVALID_USER_TOKEN" to R.string.error_login_invalid_user_token,
        "ERROR_OPERATION_NOT_ALLOWED" to R.string.error_login_operation_not_allowed,
        "ERROR_WEAK_PASSWORD" to R.string.error_login_password_is_weak)

字符串资源(可根据您的要求随意更改)

  <resources>
    <string name="error_login_custom_token">The custom token format is incorrect. Please check the documentation.</string>
    <string name="error_login_custom_token_mismatch">The custom token corresponds to a different audience.</string>
    <string name="error_login_credential_malformed_or_expired">The supplied auth credential is malformed or has expired.</string>
    <string name="error_login_invalid_email">The email address is badly formatted.</string>
    <string name="error_login_wrong_password">The password is invalid or the user does not have a password.</string>
    <string name="error_login_user_mismatch">The supplied credentials do not correspond to the previously signed in user.</string>
    <string name="error_login_requires_recent_login">This operation is sensitive and requires recent authentication. Log in again before retrying this request.</string>
    <string name="error_login_accounts_exits_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.</string>
    <string name="error_login_email_already_in_use">The email address is already in use by another account.</string>
    <string name="error_login_credential_already_in_use">This credential is already associated with a different user account.</string>
    <string name="error_login_user_disabled">The user account has been disabled by an administrator.</string>
    <string name="error_login_user_not_found">There is no user record corresponding to this identifier. The user may have been deleted.</string>
    <string name="error_login_operation_not_allowed">This operation is not allowed. You must enable this service in the console.</string>
    <string name="error_login_password_is_weak">The given password is invalid.</string>
    <string name="error_login_user_token_expired">The user\'s credential is no longer valid. The user must sign in again</string>
    <string name="error_login_invalid_user_token">The user\'s credential is no longer valid. The user must sign in again.</string>
</resources>

【讨论】:

【参考方案8】:

如果您将上游消息从用户发送到云端,请实现 firebase 回调函数 onMessageSentonSendError 以检查上游消息的状态。在错误情况下,onSendError 返回带有错误代码的 SendException

例如,如果客户端在达到 20 条消息限制后尝试发送更多消息,则返回 SendException#ERROR_TOO_MANY_MESSAGES。

【讨论】:

【参考方案9】:

我尝试了其他解决方案,但不喜欢它们。

这个呢:

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();

【讨论】:

【参考方案10】:

要捕获 firebase 异常很容易,您应该在添加 .addOnCompleteListener 之后添加 .addOnFailureListener,如下所示:

 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();
            
        
    );

【讨论】:

这样是不是有点麻烦?..和其他方法相比。【参考方案11】:

LOGIN_EXCEPTIONS

FirebaseAuthException - 与 Firebase 身份验证相关的一般异常。查看错误代码和消息以获取更多详细信息。

ERROR_USER_DISABLED 如果用户已被禁用(例如,在 Firebase 控制台中)

ERROR_USER_NOT_FOUND 如果用户已被删除(例如,在 Firebase 控制台中,或在此应用的另一个实例中)

ERROR_USER_TOKEN_EXPIRED 如果用户的令牌已在后端被撤销。如果用户的凭据在另一台设备上发生更改(例如,在密码更改事件中),这会自动发生。

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

FirebaseAuthEmailException

表示尝试通过 Firebase Auth 发送电子邮件(例如密码重置电子邮件)导致的异常

FirebaseAuthInvalidCredentialsException - 当传递给方法的一个或多个凭据无法识别和/或验证该操作的用户主体时抛出。检查错误代码和消息,找出具体原因。

FirebaseAuthWeakPasswordException - 使用弱密码(少于 6 个字符)创建新帐户或更新现有帐户密码时抛出。使用 getReason() 获取一条包含验证失败原因的消息,您可以将其显示给您的用户。

【讨论】:

【参考方案12】:

在我看来,默认消息的信息量已经足够了。所以我使用它而不是任何自定义消息,它对我来说效果很好。

if (!task.isSuccessful()) 
 
    // there was an error
    String yourString = task.getException().toString();
    String target = "Exception:";
    String error = yourString.substring(yourString.indexOf(target) + target.length() + 1, yourString.length());
    Toast.makeText(LoginScreen.this, "Error: "+error, Toast.LENGTH_LONG).show();

附言这是我关于堆栈溢出的第一个答案。如果有帮助,请告诉我。

【讨论】:

【参考方案13】:
    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
                    
        

错误代码:https://***.com/a/38244409/2425851

【讨论】:

【参考方案14】:

过去我们使用 getErrorCode() 来获取错误类型并优雅地失败。对于较新版本的 api,不推荐使用 getErrorCode()。我们应该使用 response.getError().getErrorCode() 来代替

com.firebase.ui.auth.IdpResponse
@Deprecated 
public int getErrorCode()
Get the error code for a failed sign in

Deprecated use getError() instead

所以例如

protected void onActivityResult(int requestCode, int resultCode, Intent data) 

                super.onActivityResult(requestCode, resultCode, data);

                if (requestCode == RC_SIGN_IN) 
                    IdpResponse response = IdpResponse.fromResultIntent(data);

                    // Successfully signed in
                    if (resultCode == RESULT_OK) 
                        //dbHandler = DBMS.getInstance(this);

                        FirebaseAuth auth = FirebaseAuth.getInstance();
                        FirebaseUser user = auth.getCurrentUser();
                        FirebaseUserMetadata metadata = auth.getCurrentUser().getMetadata();

                        // initialize profile first
                        if (metadata.getCreationTimestamp() == metadata.getLastSignInTimestamp()) 



                            //start main activity after profile setup
                            startActivity(new Intent(this, MainActivity.class));
                            return;
                         else 
                            // This is an existing user
                            // show them a welcome back screen.

                            startActivity(new Intent(this, MainActivity.class));
                            return;
                        
                     else 
                        // Sign in failed
                        // check response for error code
                        if (response == null) 
                            // User pressed back button
                            showSnackbar(R.string.sign_in_cancelled);
                            return;
                        

                        if (response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) 
                            showSnackbar(R.string.no_internet_connection);
                            return;
                        

                        if (response.getError().getErrorCode() == ErrorCodes.UNKNOWN_ERROR) 
                            showSnackbar(R.string.unknown_error);
                            return;
                        
                    
                    showSnackbar(R.string.unknown_sign_in_response);
                
            

【讨论】:

【参考方案15】:

尝试以下方法:

if (task.isSuccessful()) 
    //Toast.makeText(getContext(),"Registration successful", Toast.LENGTH_SHORT).show();
    try 
        Toast.makeText(getContext(),"Registration successful", Toast.LENGTH_SHORT).show();
        throw task.getException();
    
    // if user enters wrong email.
    catch (FirebaseAuthWeakPasswordException weakPassword) 
        Log.d("Registration Error", "onComplete: weak_password");

        // TODO: take your actions!
    
    // if user enters wrong password.
    catch (FirebaseAuthInvalidCredentialsException malformedEmail) 
        Log.d("Registration Error", "onComplete: malformed_email");

        // TODO: Take your action
    
    catch (FirebaseAuthUserCollisionException existEmail) 
        Log.d("Registration Error", "onComplete: exist_email");

        // TODO: Take your action
    
    catch (Exception e) 
        Log.d("Registration Error", "onComplete: " + e.getMessage());
    
 else 
    //Toast.makeText(getContext(), "ERROR, Please try again.", Toast.LENGTH_SHORT).show();
    Toast.makeText(getContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();

【讨论】:

【参考方案16】:

有太多 Firebase 身份验证异常需要处理,我不确定处理所有这些异常是否是一件好事,因为要添加大量代码(正如您从其他答案中看到的那样)。

Task&lt;AuthResult.isSuccessful() 返回 false 后,我刚刚得到了一个 FirebaseTooManyRequestsException

    firebaseAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener 
            if (it.isSuccessful) 
                [...]
             else 
                [FirebaseTooManyRequestsException and others that can be returned here]
            
        

com.google.firebase.FirebaseTooManyRequestsException: We have blocked all requests from this device due to unusual activity. Try again later. [ Access to this account has been temporarily disabled due to many failed login attempts. You can immediately restore it by resetting your password or you can try again later. ]

因此,如果您想捕获所有这些,或者至少是那些对您的逻辑更重要的,我希望将另一个 FirebaseAuth 异常添加到此列表中对您有所帮助。

【讨论】:

【参考方案17】:

你可以用这个:

mAuth.getCurrentUser().linkWithCredential(authCredential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() 
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) 
                    if (task.isSuccessful()) 
                        Log.d(TAG, "linkWithCredential:success");
                     else 
                        Log.w(TAG, "linkWithCredential:failure", task.getException());
                        Toast.makeText(getApplicationContext(), "Authentication failed. " + task.getException().toString, Toast.LENGTH_SHORT).show();

                    

                    // ...
                
            );

【讨论】:

嗨,欢迎来到 Stack Overflow。在回答已经有很多答案的问题时,请务必添加一些额外的见解,说明为什么您提供的回复是实质性的,而不是简单地呼应原始发帖人已经审查过的内容。这在您提供的“纯代码”答案中尤其重要。

以上是关于如何捕获 Firebase Auth 特定异常的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:FireBase 抛出的 PlatformException 不会被捕获

如何使用 Firebase 管理员捕获 Firebase 身份验证错误

使用 Flutter,如何在单独的登录页面小部件中显示在 AuthService 类中捕获的 Firebase Auth 错误消息?

未捕获的 TypeError: (0 , _firebase.auth) 不是函数

如何使用 Firebase (Crashlytics) 记录非致命(捕获)异常

Firebase,我如何捕获异常并告诉用户它? [复制]