0

I have the following async function:

async function register() {
  try {
    if (password1 !== password2) {
      throw "Passwords do not match!";
    }
    await firebase.auth().createUserWithEmailAndPassword(email, password1)
  }

  } catch (err) {
    document.querySelector("#message").innerHTML = err;
    return;
  }

The first password match checks if the password entered by the user two times are identical. If they are, then use Firebase to create an account. But Firebase's createUserWithEmailAndPassword function return an error object that contains a error.code and a error.message. I only want to display the error.message and disregard the error.code. Is it possible to do it with the common catch block following the try, or I have to write a specific catch block for createUserWithEmailAndPassword to disregard the error code?

Yugue Chen
  • 79
  • 5
  • [Don't throw string values!](https://stackoverflow.com/q/11502052/1048572) If you do `throw new Error("passwords do not match");` the `err` will be an object and have a `.message` property – Bergi Aug 07 '20 at 21:45

1 Answers1

2

You can try to match the structure of firebase in your Throw error condition using

   throw { message: 'Passwords do not match!' };

And then always deal with the error as an object In both cases

Edit:

Thanks to Bergi, you can also use this approach which is even better

   throw new Error('Passwords do not match!);

Which will also create an object with a message attribute

Menawer
  • 843
  • 4
  • 12