Home > Software design >  Why Catch statment not working React Js (Firebase Auth)?
Why Catch statment not working React Js (Firebase Auth)?

Time:07-15

const submitHandler = async (e) => {
    e.preventDefault();
    setErr("");
    try {
      await signUp(email, password, firstName, lastName);
      err.length === 0 &&
        setTimeout(() => {
          navigate("/");
        }, [2000]);
    } catch (error) {
      console.log(error.message);
      setErr(error.message);
    }
  };

When I submit the form with the existing email I got the error but the Catch statement not show the error.message or set the state

Getting this normal error not the message

Uncaught (in promise) FirebaseError: Firebase: Error (auth/email-already-in-use).
    at createErrorInternal (assert.ts:122:1)
    at _createError (assert.ts:83:1)
    at _makeTaggedError (index.ts:261:1)
    at _performFetchWithErrorHandling (index.ts:161:1)
    at async _performSignInRequest (index.ts:191:1)
    at async createUserWithEmailAndPassword (email_and_password.ts:23

CodePudding user response:

First of all, are you sure this signUp function throws an error?

Because it looks like this error is being handled somewhere else.. In order to catch the error, first you need to throw it.

So, for example, if there's a try catch inside signUp, you need to throw the error AGAIN in order to catch it in submitHandler.

CodePudding user response:

const submitHandler = async (e) => {
    e.preventDefault();
    //setErr("");
    try {
      await signUp(email, password, firstName, lastName);
      navigate("/");
      /*err.length === 0 &&
        setTimeout(() => {
          navigate("/");
        }, [2000]);*/
    } catch (error) {
      console.log(error);
      console.log(`code`, error.code);
      console.log(`message`, error.message);
      console.log(`name`, error.name);
      //setErr(error.message);
    }
  };
  • Related