Cómo capturar una autorización de Firebase excepciones específicas


Usando Firebase, ¿cómo capto una excepción específica y le cuento al usuario con gracia al respecto? Por ejemplo:

FirebaseAuthInvalidCredentialsException: La dirección de correo electrónico está mal formatear.

Estoy usando el siguiente código para registrar al usuario usando correo electrónico y contraseña, pero no soy tan avanzado en 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();
        }
    }    
});
Author: Devid Farinelli, 2016-06-16

13 answers

Puede lanzar la Excepción devuelta por task.getException dentro de un bloque try y capturar cada tipo de excepción que puede ser lanzada por el método que está utilizando.

Aquí hay un ejemplo del OnCompleteListener para el método 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());
    }
}
 65
Author: Steve Guidetti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-20 20:13:26

Además de la respuesta @pdegand59, encontré un código de error en la biblioteca Firebase y test en Android (el código de error devuelto). Espero que esto ayude, Saludos.

 ("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."));
 24
Author: kingspeech,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-07 11:34:22

Debe usar ((FirebaseAuthException)task.getException()).getErrorCode() para obtener el tipo de error y fallar correctamente si este es el código de error para un correo electrónico mal formateado.

Desafortunadamente, no pude encontrar la lista de códigos de error utilizados por Firebase. Active la excepción una vez, anote el código de error y el código correspondiente.

 8
Author: pdegand59,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-16 13:07:41

Si simplemente desea mostrar un mensaje al usuario, esto funciona. Simple y elegante:

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

Parece que el .El método getMessage () convierte la excepción a un formato utilizable para nosotros y todo lo que tenemos que hacer es mostrarlo en algún lugar al usuario.

(Este es mi primer comentario, crítica constructiva por favor)

 7
Author: Steven Berdak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-24 02:51:50

Hay una serie de excepciones asociadas con firebase auth. Además de @ kingspeech

Debes usar ((FirebaseAuthException)task.getException()).getErrorCode() para obtener el tipo de error y luego manejarlo en switch de la siguiente manera:

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;

                    }
                }
            }
        });
    }
 5
Author: mahmoud zaher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-12 03:36:01

Si está enviando mensajes de upstream desde user a cloud, implemente las funciones de callback de firebase onMessageSent y onSendError para comprobar el estado de los mensajes de upstream. En casos de error, onSendErrordevuelve un SendException con un código de error.

Por ejemplo, si el cliente intenta enviar más mensajes después de alcanzar el límite de 20 mensajes, devuelve SendException#ERROR_TOO_MANY_MESSAGES.

 2
Author: Anmol Bhardwaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-16 13:19:05

Puede usar el método steve-guidetti o pdegand59. Usé el método de steve-guidetti (faltan dos excepciones)

Para todas las posibles excepciones, por favor encuentre abajo ref.

Está bien documentado aquí.

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

Busca "Createuserwithemail Andpassword" y encuentra el

Códigos de error

Auth / email-ya en uso

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. 

Para las cinco excepciones: Marque aquí

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

Aquí puedes encontrar 5 tipos diferentes de AuthException. 4 Subclase Directa Conocida y 1 subclase indirecta

Puedes usar steve-guidetti o método pdegand59.

 2
Author: Itzdsp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-30 17:56:04

Probé otras soluciones pero no me gustaron.

¿Qué hay de esto:

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();
}
 2
Author: RedLEON,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-09 14:52:38

LOGIN_EXCEPTIONS

FirebaseAuthException - Excepción genérica relacionada con la autenticación Firebase. Consulte el código de error y el mensaje para obtener más detalles.

ERROR_USER_DISABLED si el usuario ha sido deshabilitado (por ejemplo, en la consola Firebase)

ERROR_USER_NOT_FOUND si el usuario ha sido eliminado (por ejemplo, en la consola Firebase, o en otra instancia de esta aplicación)

ERROR_USER_TOKEN_EXPIRED si el token del usuario ha sido revocado en el backend. Esto sucede automáticamente si las credenciales del usuario cambio en otro dispositivo (por ejemplo, en un evento de cambio de contraseña).

ERROR_INVALID_USER_TOKEN si el token del usuario está mal formado. Esto no debería ocurrir en circunstancias normales.

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

Representa la excepción que es el resultado de un intento de enviar un correo electrónico a través de Firebase Auth (por ejemplo, un correo electrónico de restablecimiento de contraseña)

FirebaseAuthInvalidCredentialsException - Se lanza cuando una o más de las credenciales pasadas a un método fallan en identificar y / o autenticar el sujeto del usuario de esa operación. Inspeccione el código de error y el mensaje para averiguar la causa específica.

FirebaseAuthWeakPasswordException - Lanzado cuando se utiliza una contraseña débil (menos de 6 caracteres) para crear una nueva cuenta o para actualizar la contraseña de una cuenta existente. Use getReason () para obtener un mensaje con la razón por la que falló la validación que puede mostrar a sus usuarios.

 1
Author: Diego Venâncio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 00:06:24
    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
                    }
        }

Códigos de error: https://stackoverflow.com/a/38244409/2425851

 0
Author: NickUnuchek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:45

Para capturar una excepción de base de fuego es fácil, debe agregar .addOnFailureListener después de agregar .addOnCompleteListener de la siguiente manera:

 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();
            }
        }
    });
 0
Author: Ra Isse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-14 14:02:38

En el pasado usamos getErrorCode() para obtener el tipo de error y fallar correctamente. Con las versiones más recientes de la api, getErrorCode () está obsoleta. Deberíamos usar la respuesta.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

Así que para, por ejemplo,

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
Author: Mr.hands-on,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-30 11:25:10

Intente lo siguiente:

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
Author: AUSiBi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-01 09:22:01