How to Catch a Firebase Auth Specific Exceptions

How to Handle Firebase Auth exceptions on flutter

(21/02/20) EDIT: This answer is old and the other answers contains cross platform solutions so you should look at theirs first and treat this as a fallback solution.

The firebase auth plugin doesn't really have a proper cross-platform error code system yet so you have to handle errors for android and ios independently.

I'm currently using the temporary fix from this github issue: #20223

Do note since its a temp fix, don't expect it to be fully reliable as a permanent solution.

enum authProblems { UserNotFound, PasswordNotValid, NetworkError }

try {
FirebaseUser user = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
} catch (e) {
authProblems errorType;
if (Platform.isAndroid) {
switch (e.message) {
case 'There is no user record corresponding to this identifier. The user may have been deleted.':
errorType = authProblems.UserNotFound;
break;
case 'The password is invalid or the user does not have a password.':
errorType = authProblems.PasswordNotValid;
break;
case 'A network error (such as timeout, interrupted connection or unreachable host) has occurred.':
errorType = authProblems.NetworkError;
break;
// ...
default:
print('Case ${e.message} is not yet implemented');
}
} else if (Platform.isIOS) {
switch (e.code) {
case 'Error 17011':
errorType = authProblems.UserNotFound;
break;
case 'Error 17009':
errorType = authProblems.PasswordNotValid;
break;
case 'Error 17020':
errorType = authProblems.NetworkError;
break;
// ...
default:
print('Case ${e.message} is not yet implemented');
}
}
print('The error is $errorType');
}

How to catch a Firebase Auth specific exceptions

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

Firebase Catch Exceptions + List of Firebase Exceptions Kotlin

You can find the list of possible errors produced by Firebase Auth APIs in the API documentation. They are all subclasses of FirebaseAuthException:

FirebaseAuthActionCodeException, FirebaseAuthEmailException, FirebaseAuthInvalidCredentialsException, FirebaseAuthInvalidUserException, FirebaseAuthMultiFactorException, FirebaseAuthRecentLoginRequiredException, FirebaseAuthUserCollisionException, FirebaseAuthWebException

See also:

  • How to catch a Firebase Auth specific exceptions
  • How to handle FirebaseAuth exceptions

what are the error codes for Flutter Firebase Auth Exception?

For the signInWithEmailAndPassword method for Flutter, you will find the error codes in the firebase_auth package documentation.

They are actually the same than the JS SDK ones: https://firebase.google.com/docs/reference/js/firebase.auth.Auth#error-codes_12

Catching errors in Flutter / Firebase Auth sign up

    FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _email, password: _password)
.then((currentUser) => {
//Execute
}).catchError((onError)=>{
//Handle error i.e display notification or toast
});

This code actually works but the editor (Visual Studio code) itself is throwing exceptions and crashing the app , if you run the app from the device or emulator itself the issue will be solved

Google Firebase how to catch specific Auth exception errors - Unity

The answer is simple- either use the following function on the task you are trying to achieve -

protected bool LogTaskCompletion(Task task, string operation)
{
bool complete = false;
if (task.IsCanceled)
{
Debug.Log(operation + " canceled.");
}
else if (task.IsFaulted)
{
Debug.Log(operation + " encounted an error.");
foreach (Exception exception in task.Exception.Flatten().InnerExceptions)
{
string authErrorCode = "";
Firebase.FirebaseException firebaseEx = exception as Firebase.FirebaseException;
if (firebaseEx != null)
{
authErrorCode = String.Format("AuthError.{0}: ",
((Firebase.Auth.AuthError)firebaseEx.ErrorCode).ToString());
}
Debug.Log("number- "+ authErrorCode +"the exception is- "+ exception.ToString());
string code = ((Firebase.Auth.AuthError)firebaseEx.ErrorCode).ToString();
Debug.Log(code);
}
}
else if (task.IsCompleted)
{
Debug.Log(operation + " completed");
complete = true;
}
return complete;
}

The printed output Debug.Log(code) is the exception code you are looking for. Now you can compare it - if (code.Equals("some specific exception....")) and complete it with your code.

Example:

How to catch if user/email exists
Let's say we sign up a new user with CreateUserWithEmailAndPasswordAsync and we want to catch the error " The email address is already in use"
We can use my function to find out what the error code we need to compare and it will print to output "EmailAlreadyInUse". Next all I need to do is to check if ((code).Equals("EmailAlreadyInUse"))
-Another possible way is to find the error code in a list-

List of Auth exceptions error code FOR UNITY
All the exceptions are under class Firebase.Auth.AuthError you can see them either on your code editor, or on Firebase website under - Unity - Firebase.Auth - Overview (under AuthError).

Hope it helps!

How to handle FirebaseAuth exceptions

FirebaseAuth.getInstance().createUserWithEmailAndPassword("EMAIL", "PASSWORD")
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
// thrown if there already exists an account with the given email address
} else if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// thrown if the email address is malformed
} else if (task.getException instanceof FirebaseAuthWeakPasswordException) {
// thrown if the password is not strong enough
}
}
}
});


Related Topics



Leave a reply



Submit