How to catch a Firebase Auth specific exceptions

前端 未结 16 2239
慢半拍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:20

    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.

    Unfortunately, I couldn't find the list of error codes used by Firebase. Trigger the exception once, note the error code and code accordingly.

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

    You can use either steve-guidetti or pdegand59 method. I used steve-guidetti's method(Two exceptions are missing)

    For all possible exception please find below ref.

    It is well documented here.

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

    Search for "createUserWithEmailAndPassword" and find the

    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

    Here you can find 5 different types of AuthException. 4 Known Direct subclass and 1 indirect subclass

    You can use either steve-guidetti or pdegand59 method.

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

    SOLUTION WITH KOTLIN

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

    Explanation: Basically It's just a map that match firebase error codes with a custom string resource.

    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)
    

    String resources (Feel free to change it according to your requirements)

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

    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.

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

    LOGIN_EXCEPTIONS

    FirebaseAuthException - Generic exception related to Firebase Authentication. Check the error code and message for more details.

    ERROR_USER_DISABLED if the user has been disabled (for example, in the Firebase console)

    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_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_INVALID_USER_TOKEN if the user's token is malformed. This should not happen under normal circumstances.

    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
    

    Represents the exception which is a result of an attempt to send an email via Firebase Auth (e.g. a password reset email)

    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.

    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.

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

    Try the following:

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