How to Create Custom Error in Node.js: Simple Guide
In Node.js, create a custom error by extending the built-in
Error class with your own class. Define a constructor that calls super(message) to set the error message and optionally add custom properties.Syntax
To create a custom error, define a class that extends Error. Inside the constructor, call super(message) to set the error message. You can add extra properties if needed.
- class CustomError extends Error: Defines a new error type.
- constructor(message): Receives the error message.
- super(message): Calls the parent
Errorconstructor. - this.name: Sets the error 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 to handle the error gracefully.
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(150); } catch (error) { if (error instanceof ValidationError) { console.log('Validation failed:', error.message); } else { console.log('Unknown error:', error); } }
Output
Validation failed: Age must be between 0 and 120
Common Pitfalls
Common mistakes when creating custom errors include:
- Not calling
super(message)in the constructor, which breaks the error message setup. - Forgetting to set
this.name, making it harder to identify the error type. - Throwing plain objects or strings instead of error instances, which breaks stack traces.
javascript
/* Wrong way: Missing super call and name */ class BadError extends Error { constructor(message) { super(message); this.message = message; // Added super call } } /* Right way: */ class GoodError extends Error { constructor(message) { super(message); this.name = 'GoodError'; } }
Quick Reference
Remember these tips when creating custom errors in Node.js:
- Always extend
Error. - Call
super(message)in the constructor. - Set
this.nameto your error class name. - Throw instances of your custom error for clear stack traces.
Key Takeaways
Create custom errors by extending the built-in Error class in Node.js.
Always call super(message) in the constructor to set the error message.
Set this.name to your custom error class name for easier identification.
Throw instances of your custom error to keep proper stack traces.
Avoid throwing plain strings or objects to maintain error consistency.