MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Throwing Custom Errors0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
9.1try...catch9.2finally block9.3Throwing Custom Errors9.4Error Handling in Async Code
HomeTutorialsJavaScript for IntermediateThrowing Custom Errors
Error Handling in Async Code

Throwing Custom Errors

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

While JavaScript provides standard error primitives (TypeError, ReferenceError), real-world enterprise applications require domain-specific errors (e.g., ValidationError, AuthenticationError, DatabaseConnectionError). Creating custom error classes allows upstream consumers to distinguish between different failure modes and handle them accordingly.


1. The throw Statement

You can throw any expression in JavaScript, but you should always throw instances of Error (or classes extending Error) to ensure stack traces are preserved:

1// ANTI-PATTERN: Throwing raw strings or numbers loses stack traces!
2// throw "Password too short";
3 
4// BEST PRACTICE:
5throw new Error("Password must be at least 8 characters long.");

2. Creating Custom Error Classes

In modern ES6+, inherit from the built-in Error superclass:

1class ValidationError extends Error {
2 constructor(message, fieldName = null) {
3 super(message); // Call super constructor with error message
4 this.name = 'ValidationError';
5 this.fieldName = fieldName;
6 this.date = new Date();
7 }
8}
9 
10class InsufficientFundsError extends Error {
11 constructor(balance, required) {
12 super(`Transaction rejected: Available balance $${balance}, required $${required}`);
13 this.name = 'InsufficientFundsError';
14 this.balance = balance;
15 this.required = required;
16 }
17}

3. Differentiating Errors with instanceof

When catching errors, use instanceof to route different errors to specific recovery routines:

1function withdrawFunds(account, amount) {
2 if (amount <= 0) {
3 throw new ValidationError('Withdrawal amount must be greater than zero.', 'amount');
4 }
5 if (account.balance < amount) {
6 throw new InsufficientFundsError(account.balance, amount);
7 }
8 account.balance -= amount;
9 return account.balance;
10}
11 
12try {
13 withdrawFunds(userAccount, 500);
14} catch (error) {
15 if (error instanceof ValidationError) {
16 // Highlight input field in Red on the UI
17 showFieldHighlight(error.fieldName, error.message);
18 } else if (error instanceof InsufficientFundsError) {
19 // Show 'Add Funds' modal
20 openDepositModal(error.required - error.balance);
21 } else {
22 // Unrecognized runtime crash (rethrow or send to Sentry)
23 console.error('Unexpected crash:', error);
24 throw error;
25 }
26}

4. Error Chaining with { cause } (ES2022)

Often, a low-level error (like a disk failure or database timeout) causes a higher-level business error. ES2022 introduced the { cause } option to chain the original root error:

1async function loadUserData(userId) {
2 try {
3 return await api.get(`/users/${userId}`);
4 } catch (originalNetworkError) {
5 // Wrap low-level error inside a domain error while preserving cause!
6 throw new Error(`Failed to load profile for user ${userId}`, {
7 cause: originalNetworkError
8 });
9 }
10}
11 
12// In consumer:
13try {
14 await loadUserData(42);
15} catch (err) {
16 console.log(err.message); // 'Failed to load profile for user 42'
17 console.log(err.cause.message); // 'ETIMEDOUT: Connection to server timed out'
18}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why should you extend the built-in Error class instead of throwing plain strings?
Question 2
What keyword must be called inside the constructor of a custom class extending Error?
Question 3
How do you identify which specific custom error was caught in a catch block?
Question 4
What feature was introduced in ES2022 to preserve the original underlying error when throwing a higher-level error?
Question 5
What should you do in a catch block if the caught error is not an expected domain error?
Next Lesson

Error Handling in Async Code

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
finally blockError Handling in Async Code

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext