How to handle errors in the new Firebase sdk for authentication? In the previous versions i can find the OnAuthenticationError method and it gives FirebaseException error but in the new verison i dont see such method. Lets say i create a user by email password,for some reason exception occurs . The only way i can see to grab this exception is the task.getException.getMessage() and with this message i check for various error messages and then in turn get the error which occured. Please suggest a better method or correct me if i m missing something
Asked
Active
Viewed 3,318 times
2 Answers
2
The main exceptions:
firebaseAuth.createUserWithEmailAndPassword(email, pass )
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
//--If success
}else if (task.getException() instanceof FirebaseAuthUserCollisionException)
{
//If email already registered.
}else if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
//If email are in incorret format
}else if (task.getException() instanceof FirebaseAuthWeakPasswordException) {
//if password not 'stronger'
}else
{
//OTHER THING
}
}
});

Diego Venâncio
- 5,698
- 2
- 49
- 68
1
In the new Firebase a lot of methods return a so-called Task
. If you've used promises in JavaScript before, you'll find they're very similar.
On the task, you can get a few callbacks:
- a success listener, which gets invoked once the task succeeds
- a failure listener, which gets invoked once the task fails
- a completion listener, which gets invoked once the task completes (successfully or not)
In your case you're looking for a failure in creating a user, so:
auth.createUserWithEmailAndPassword(email, password)
.addOnFailureListener(new OnFailureListener() {
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Unable to create user", e);
}
});
The exception will be a subclass of FirebaseAuthException
, which means you can call getErrorCode()
on it. This returns an error code. It's indeed a string, but of a form auth/error
which can be easily captured in a switch case.
Also see the documentation on creating a user for a sample that uses a completion listener.

Frank van Puffelen
- 565,676
- 79
- 828
- 807
-
Thanks for your reply. If i add onFailureListener then in the overriden onFailure method i get a parameter java 'Exception' in which i can get only the error message, with this message i have to iterate over all several predefined strings by me to handle this exception. I was looking for a better method as of old firebase sdk. – Ayush P Gupta Jun 12 '16 at 16:56
-
I indeed had the signature wrong. I now captured it in Android Studio for you convenience. The 2.x SDK had a numeric error code. Handling all string error codes isn't much different. – Frank van Puffelen Jun 12 '16 at 22:46