How to Create Custom Error in JavaScript: Simple Guide
To create a custom error in JavaScript, define a new class that extends the built-in
Error class and set a custom name property. This lets you throw and catch errors with specific types for better debugging and control.Syntax
Use a class that extends Error. Inside the constructor, call super(message) to set the error message, and set this.name to your custom error name.
class: defines the custom error typeextends Error: inherits from JavaScript's built-in errorconstructor(message): receives the error messagesuper(message): passes message to the base Error classthis.name: sets the error's name for identification
javascript
class CustomError extends Error { constructor(message) { super(message); this.name = 'CustomError'; } }
Example
This example shows how to create and throw a custom error, then catch it and check its type.
javascript
class ValidationError extends Error { constructor(message) { super(message); this.name = 'ValidationError'; } } function validateAge(age) { if (age < 0 || age > 120) { throw new ValidationError('Age must be between 0 and 120'); } return true; } try { validateAge(-5); } catch (error) { if (error instanceof ValidationError) { console.log('Caught a validation error:', error.message); } else { console.log('Unknown error:', error); } }
Output
Caught a validation error: Age must be between 0 and 120
Common Pitfalls
Common mistakes include forgetting to call super(message) in the constructor, which breaks the error message setup, or not setting this.name, making it harder to identify the error type. Also, avoid using plain objects or strings as errors because they lack stack traces and type information.
javascript
/* Wrong way: missing super call and name */ class BadError extends Error { constructor(message) { // super(message) is missing super(); this.message = message; } } /* Right way: call super and set name */ class GoodError extends Error { constructor(message) { super(message); this.name = 'GoodError'; } }
Quick Reference
Remember these key points when creating custom errors:
- Always extend the built-in
Errorclass. - Call
super(message)in the constructor. - Set
this.nameto your custom error's name. - Use
instanceofto check error types when catching.
Key Takeaways
Create custom errors by extending the built-in Error class.
Always call super(message) in your custom error constructor.
Set this.name to identify your custom error type clearly.
Use instanceof to detect your custom errors in catch blocks.
Avoid using plain objects or strings as errors for better debugging.