Does Firebase Auth return an Error Code if authentification is not successful?

Viewed 2774

I'm building a login flow with Firebase Auth to authenticate users with email and password. While logging in, some things can go wrong: No account exists with the given email address, the password is wrong (...).

Does Firebase return any error code so I can add error handling? I only found the exception messages which I can use for error handling but is there any way to make this neater with error codes? I couldn't find anything in the official Firebase documentation.

    auth.signInWithEmailAndPassword(email, password).addOnCompleteListener { task ->
        if (task.isSuccessful) {
            // Sign in success, update UI with the signed-in user's information
            Log.d(TAG, "signInWithEmail:success")
        } 
    }.addOnFailureListener { exception: Exception ->
        when (exception.message) {
            "There is no user record corresponding to this identifier. The user may have been deleted." -> // Handle error
            "The password is invalid or the user does not have a password." ->// Handle error
            else -> // Handle error
        }
    }
1 Answers

Does Firebase return any error code so I can add error handling?

Sure it does. FirebaseAuthException class contains a method called getErrorCode() that:

Returns an error code that may provide more information about the error.

Besides that, in the above documentation you'll also find two very useful sections:

  1. Known Direct Subclasses:

And:

  1. Known Indirect Subclasses:

So you can always get a specific message according to the particular Exception that is thrown.

Edit:

I was wondering is where to get a list of all error codes.

Firebase Auth doesn't provide a full list of errors. The linked answer, might be considered a little old, as it is added on Jul 7 '16. Since then, Firebase Authentication SDK got some changes. If you are interested in error codes, you should check each type of Exception. For instance, a known direct subclass of FirebaseAuthException, is called FirebaseAuthInvalidUserException. Inside this class, you might see some error codes:

  • ERROR_USER_DISABLED
  • ERROR_USER_NOT_FOUND
  • ERROR_USER_TOKEN_EXPIRED
  • ERROR_INVALID_USER_TOKEN.

So the best option that you have is to look inside each specific class.

This isn't available only in the case of authentication, it's available in the case of all the other Exception classes. For example, if we are talking about Cloud Firestore, the corresponding Exception is called FirebaseFirestoreException and contains inside an enum with error codes. Here are the values:

  • ABORTED
  • ALREADY_EXISTS
  • CANCELLED
  • DATA_LOSS
  • DEADLINE_EXCEEDED
  • FAILED_PRECONDITION
  • INTERNAL
  • INVALID_ARGUMENT
  • NOT_FOUND
  • OK
  • OUT_OF_RANGE
  • PERMISSION_DENIED
  • RESOURCE_EXHAUSTED
  • UNAUTHENTICATED
  • UNAVAILABLE
  • UNIMPLEMENTED
  • UNKNOWN
Related