Home > Software design >  How to Handle Firebase Auth exceptions on flutter
How to Handle Firebase Auth exceptions on flutter

Time:01-01

I can't handle an error if the user tries to sign up using an already existing email

Future _createUser(Users user, String name, x) async {
    UserCredential result = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(
            email: _emailController.text.trim(),
            password: _passwordController.text.trim());
    try {
      result;
    } on FirebaseAuthException catch (e) {
      if (e.code == 'firebase_auth/email-already-in-use') {
        final snackBarx = SnackBar(
          elevation: 0,
          behavior: SnackBarBehavior.floating,
          backgroundColor: Colors.transparent,
          content: AwesomeSnackbarContent(
            message: 'Error please log in again and try again',
            contentType: ContentType.failure,
          ),
        );
        ScaffoldMessenger.of(context)
          ..hideCurrentSnackBar()
          ..showSnackBar(snackBarx);

CodePudding user response:

In my application I handle like this:

try {
  result;
} on FirebaseAuthException catch (error) {
  if (error.code == "wrong-password") {

    //Handle error from Wrong Password

  } else if (error.code == "user-not-found") {

    //Handle error User Not Found

  } else if (error.code == "invalid-email") {
    
    //Handle error from Invalid Email

  } else if (error.code == "too-many-requests") {

    //Handle error from Too Many Requests        

  } else if (error.code == "network-request-failed") {
    
    //Handle error from NetWork failure

  }
}

CodePudding user response:

Use this function:

 static String getAuthErrorMessage(FirebaseAuthException ex) {
    if (ex.code == "invalid-verification-code") {
      return "Invalid OTP";
    } else if (ex.code == "code-expired") {
      return "Code expired. Try again with new code";
    } else if (ex.code == "internal-error") {
      return "Unknown error. Please try again after sometime";
    } else if (ex.code == "invalid-phone-number") {
      return "Invalid phone number";
    } else if (ex.code == "invalid-verification-id") {
      return "Invalid verification id";
    } else if (ex.code == "quota-exceeded") {
      return "We are receiving too many requests. Please try again after sometime";
    } else if (ex.code == "timeout") {
      return "Timeout. Please verify again";
    } else if (ex.code == "too-many-requests") {
      return "We are receiving too many requests. Try again after sometime";
    }

    return ex.message.toString();
  }

Use it as:

 void signInWithPhone(PhoneAuthCredential credential) async {
    try {
      UserCredential userCredential =
          await _auth.signInWithCredential(credential);
    } on FirebaseAuthException catch (ex) {
      print(getAuthErrorMessage(ex));      //           
  • Related