Explore Topics

How to Create Custom Error in JavaScript?

Last Updated : 18 Apr, 2025 - Asked By Ashok

javascript  create custom error 

Answers
2023-12-01 11:56:18

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
Certification

Earn certifications to enhance your resume.

Q&A Image
Q&A

Hands-on projects to improve your skills.

People Also Asked