Skip to main content

How to Create Custom Error in JavaScript?

Published: Asked By 1 Answers Answered

Learn how to create custom errors in JavaScript. Explore using the Error class and custom messages to handle exceptions effectively and improve debugging in your applications.

Share:

1 Answer

S
Sooraj Community Contributor Answered on

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  }
}

 

  In the above example, we create a new class called CustomError that extends the built-in Error class. We then define a constructor function that takes a message parameter and passes it to the super() method, which calls the parent constructor. We also set the name property of the error to "CustomError".

Once you have defined your custom error, you can throw it like any other error:

           throw new CustomError("Something went wrong!");
 

Your Answer

Other Resources

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

Q&A Image
Q&A

Ask your coding-related doubts and get answers.

Certification Image
Certification

Earn certifications to enhance your resume.

internships Image
Internships

Hands-on projects to improve your skills.

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

blog Image
Blogs

Add your technical blogs and read technical topics.

Certification Image
Certifications

Earn certifications to enhance your resume.