Throwing Custom Errors
Throwing Custom Errors in Modern JavaScript
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:
2. Creating Custom Error Classes
In modern ES6+, inherit from the built-in Error superclass:
3. Differentiating Errors with instanceof
When catching errors, use instanceof to route different errors to specific recovery routines:
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:
Practice Quiz
Error Handling in Async Code
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| finally block | Error Handling in Async Code |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.