programing

Firebase Auth 관련 예외를 검색하는 방법

muds 2023. 7. 5. 21:05
반응형

Firebase Auth 관련 예외를 검색하는 방법

Firebase를 사용하여 특정 예외를 감지하고 사용자에게 우아하게 알려주는 방법은 무엇입니까?예:

파이어베이스AuthInvalid 자격 증명예외:전자 메일 주소의 형식이 잘못되었습니다.

저는 아래 코드를 사용하여 이메일과 비밀번호를 사용하여 사용자를 등록하고 있지만, 저는 자바가 그렇게 발달하지 않았습니다.

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▁returned에서 반환된 를 던질 수 .task.getException사용 중인 메서드에 의해 던져질 수 있는 각 유형의 예외를 검색합니다.

▁the의 .OnCompleteListener를해위를 .createUserWithEmailAndPassword방법.

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

@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.";

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;

                    }
                }
            }
        });
    }

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

설명:기본적으로 파이어베이스 오류 코드와 사용자 지정 문자열 리소스를 일치시키는 맵입니다.

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>

당신은 야합다니해를 사용해야 .((FirebaseAuthException)task.getException()).getErrorCode()잘못된 형식의 전자 메일에 대한 오류 코드인 경우 오류 유형을 가져오고 정상적으로 실패합니다.

안타깝게도 파이어베이스에서 사용하는 에러 코드 목록을 찾을 수 없었습니다.예외를 한 번 트리거하고 오류 코드와 코드를 기록합니다.

단순히 사용자에게 메시지를 표시하려는 경우 이 기능이 작동합니다.단순하고 우아함:

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() 메서드는 이미 예외를 사용 가능한 형식으로 변환한 것으로 보이며 사용자에게 표시하기만 하면 됩니다.

(이것은 저의 첫 번째 논평입니다, 건설적인 비평 부탁드립니다)

Steve-guidetti 또는 pdegand59 방법을 사용할 수 있습니다.Steve-guidetti의 방법을 사용했습니다(두 가지 예외가 누락되었습니다).

가능한 모든 예외에 대해 아래 참조하십시오.

이것은 여기에 잘 기록되어 있습니다.

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

"이메일 및 암호를 사용하여 사용자 만들기"를 검색하고 다음을 찾습니다.

오류 코드

사용 중인 인증/이메일

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 방법을 사용할 수 있습니다.

기능을 합니다.onMessageSent그리고.onSendError업스트림 메시지의 상태를 확인합니다.오류가 발생한 경우onSendError오류 코드가 있는 SendException을 반환합니다.

예를 들어, 20개 메시지 제한에 도달한 후 클라이언트가 더 많은 메시지를 보내려고 하면 SendException#ERROR_TOU_MANY_MESSAGS를 반환합니다.

파이베를잡예외쉽합추니다야가해게를면을 ..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();
            }
        }
    });

저는 다른 해결책을 시도해 보았지만 마음에 들지 않았습니다.

다음은 어떻습니까?

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

로그인_예외

FirebaseAuthExceptionFirebase 인증과 관련된 일반 예외입니다.자세한 내용은 오류 코드 및 메시지를 확인하십시오.

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 "))
         {
         }
 }
});

레지스터_예외

FirebaseAuthEmailException

Firebase Auth(예: 암호 재설정 전자 메일)를 통해 전자 메일을 보내려는 시도의 결과인 예외를 나타냅니다.

FirebaseAuthInvalidCredentialsException메서드에 전달된 하나 이상의 자격 증명이 해당 작업의 사용자 주체를 식별 및/또는 인증하지 못할 때 느려집니다.오류 코드 및 메시지를 검사하여 특정 원인을 찾습니다.

FirebaseAuthWeakPasswordException약한 암호(6자 미만)를 사용하여 새 계정을 만들거나 기존 계정의 암호를 업데이트할 때 느려집니다.을 사용하여 할 수 검사에 합니다. getReason()은 과 같습니다

저에 따르면 기본 메시지는 충분히 유용합니다.그래서 저는 어떤 사용자 지정 메시지보다 그것을 사용했고 그것은 저에게 꽤 잘 작동했습니다.

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. 스택 오버플로에 대한 첫 번째 답변입니다.도움이 되었는지 알려주세요.

    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://stackoverflow.com/a/38244409/2425851

이전에는 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);
                }
            }

다음을 시도합니다.

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

Firebase Authentication 예외를 처리하기에는 너무 많고, 추가할 코드의 양이 많아 모두 처리하는 것이 좋은 일인지 모르겠습니다(다른 답변에서 알 수 있듯이).

방금 전에.FirebaseTooManyRequestsException끝나고Task<AuthResult.isSuccessful()false를 반환했습니다.

    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. ]

FirebaseTooManyRequestsException

그래서, 만약 당신이 그들을 모두 잡거나 적어도 당신의 논리에 더 중요한 것들을 잡고 싶다면, 저는 다른 파이어베이스를 가져오길 바랍니다.이 목록에 대한 인증 예외가 도움이 됩니다.

여기에Kotlin내가 사용하는 파서.파이어베이스에서 각색되었습니다.UI-Android

/**
 * List of all possible results of [FirebaseAuthException.getErrorCode] and their meanings.
 * TODO you can make description parameter private if you don't use it outside of this class
 */
enum class FirebaseAuthErrorParser(val description: String) {
    ERROR_INVALID_CUSTOM_TOKEN("The custom token format is incorrect. Please check the documentation."),
    ERROR_CUSTOM_TOKEN_MISMATCH("Invalid configuration. Ensure your app's SHA1 is correct in the Firebase console."),
    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 has expired. 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. Enable the sign-in method in the Authentication tab of the Firebase console"),
    ERROR_TOO_MANY_REQUESTS("We have blocked all requests from this device due to unusual activity. Try again later."),
    ERROR_WEAK_PASSWORD("The given password is too weak, please choose a stronger password."),
    ERROR_EXPIRED_ACTION_CODE("The out of band code has expired."),
    ERROR_INVALID_ACTION_CODE("The out of band code is invalid. This can happen if the code is malformed, expired, or has already been used."),
    ERROR_INVALID_MESSAGE_PAYLOAD("The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console."),
    ERROR_INVALID_RECIPIENT_EMAIL("The email corresponding to this action failed to send as the provided recipient email address is invalid."),
    ERROR_INVALID_SENDER("The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console."),
    ERROR_MISSING_EMAIL("An email address must be provided."),
    ERROR_MISSING_PASSWORD("A password must be provided."),
    ERROR_MISSING_PHONE_NUMBER("To send verification codes, provide a phone number for the recipient."),
    ERROR_INVALID_PHONE_NUMBER("The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code]."),
    ERROR_MISSING_VERIFICATION_CODE("The phone auth credential was created with an empty sms verification code"),
    ERROR_INVALID_VERIFICATION_CODE("The sms verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure use the verification code provided by the user."),
    ERROR_MISSING_VERIFICATION_ID("The phone auth credential was created with an empty verification ID"),
    ERROR_INVALID_VERIFICATION_ID("The verification ID used to create the phone auth credential is invalid."),
    ERROR_RETRY_PHONE_AUTH("An error occurred during authentication using the PhoneAuthCredential. Please retry authentication."),
    ERROR_SESSION_EXPIRED("The sms code has expired. Please re-send the verification code to try again."),
    ERROR_QUOTA_EXCEEDED("The sms quota for this project has been exceeded."),
    ERROR_APP_NOT_AUTHORIZED("This app is not authorized to use Firebase Authentication. Please verify that the correct package name and SHA-1 are configured in the Firebase Console."),
    ERROR_API_NOT_AVAILABLE("The API that you are calling is not available on devices without Google Play Services."),
    ERROR_WEB_CONTEXT_CANCELED("The web operation was canceled by the user"),
    ERROR_UNKNOWN("An unknown error occurred.");


    companion object {
        /**
         * Get an [FirebaseAuthError.description] from an exception,
         * returning [FirebaseAuthError.ERROR_UNKNOWN] as a default.
         */
        fun fromException(ex: FirebaseAuthException): String {
            return try {
                valueOf(ex.errorCode).description
            } catch (e: IllegalArgumentException) {
                Log.e(TAG, e)
                ERROR_UNKNOWN.description
            }
        }
    }
}

사용 방법은 다음과 같습니다.

val ErrorMsg = FirebaseAuthErrorParser.fromException(firebaseAuthEx)

다음을 사용할 수 있습니다.

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

                    }

                    // ...
                }
            });

언급URL : https://stackoverflow.com/questions/37859582/how-to-catch-a-firebase-auth-specific-exceptions

반응형