Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass custom message to catch error block with throw error

I want to create custom error message and be able to read it in my catch block, how can I achieve this? I want to make erorMessage in catch block with the text that throw Error passes and be able to display custom error message. However when I try to log (err)

const password = "test";
const repeatPassword = "test1";
let errorMessage = "";

const handleSubmit = () => {
    if(password != repeatPassword) {
    throw Error("Passwords must match");
  }
  
  try {
    console.log("trying");
  } catch(err) {
    errorMessage = err;
    console.log(err);
  }
}

handleSubmit();

am I approaching this in wrong way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

just move your try above like this

    const handleSubmit = () => {
      try {
        console.log("trying");
        if(password != repeatPassword) {
        throw Error("Passwords must match");
        }
      } catch(err) {
        errorMessage = err;
        console.log(err);
      }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading