How to catch a Firebase Auth specific exceptions

前端 未结 16 2250
慢半拍i
慢半拍i 2020-11-28 04:37

Using Firebase, how do I catch a specific exception and tell the user gracefully about it? E.g :

FirebaseAuthInvalidCredentialsException: The email ad

相关标签:
16条回答
  • 2020-11-28 05:29

    In the past we used the getErrorCode() to get the type of error and fail gracefully. With the newer versions of the api, getErrorCode() is deprecated. We should use response.getError().getErrorCode() instead

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

    So for e.g.

    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);
                    }
                }
    
    0 讨论(0)
  • 2020-11-28 05:30

    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.

    Here is an example from the OnCompleteListener for the createUserWithEmailAndPassword method.

    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());
        }
    }
    
    0 讨论(0)
  • 2020-11-28 05:30

    According to me the default message is informative enough. So I used it rather than any custom message and it worked pretty well for me.

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

    p.s. this is my first answer on stack overflow. Do let me know if it was helpful.

    0 讨论(0)
  • 2020-11-28 05:31

    There are a number of exceptions associated with firebase auth. In addition to @kingspeech

    You should use ((FirebaseAuthException)task.getException()).getErrorCode() to get the type of error and then handle it in switch like this :

    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;
    
                        }
                    }
                }
            });
        }
    
    0 讨论(0)
提交回复
热议问题