How to catch a Firebase Auth specific exceptions

Relm picture Relm · Jun 16, 2016 · Viewed 47.3k times · Source

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

FirebaseAuthInvalidCredentialsException: The email address is badly formatted.

I'm using the code below to signup the user using email and password, but I'm not that advanced in 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();
        }
    }    
});

Answer

Steve Guidetti picture Steve Guidetti · Jul 20, 2016

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