user3561607 user3561607 - 2 months ago 19
Android Question

How to override exception of createUserWithEmailAndPassword method?

I'm using Firebase and I'm using a method to create an account for users which called "createUserWithEmailAndPassword".

I found in Firebase references that one of this method exceptions is "FirebaseAuthWeakPasswordException" which called when the password is less than 6 characters.

I want to catch this exception and show the user a message with my own words,
but when I wrap the method with try&catch I get this error: "Exception 'com.google.firebase.auth.FirebaseAuthWeakPasswordException' is never thrown in the corresponding try block".
I tried to fix this for a while, but no luck.
here is a snippet of the code, hope you can help my figure this out:

mAuth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {

@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());

// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.

if(task.isSuccessful())
{
Toast.makeText(getApplicationContext(),"Account has created!",Toast.LENGTH_SHORT).show();
}
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "failed!",
Toast.LENGTH_SHORT).show();
}
}

});

Answer

You have not added any FailureListener that's why you can't get correct error code or exception.

Add it to mAuth like this

mAuth.createUserWithEmailAndPassword(email, pass)
      .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        if (e instanceof FirebaseAuthException) {
                            ((FirebaseAuthException) e).getErrorCode());
                           //your other logic goes here
                      }
                    }
                })

Do let me know if it changes anything for you.

Comments