Relm Relm - 11 months ago 212
Android Question

How to catch a Firebase Auth specific exceptions

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

FirebaseAuthInvalidCredentialsException: The email address is badly

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

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 Source

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) {
    } catch(FirebaseAuthInvalidCredentialsException e) {
    } catch(FirebaseAuthUserCollisionException e) {
    } catch(Exception e) {
        Log.e(TAG, e.getMessage());