Custom error classes help you create specific error types. This makes it easier to find and fix problems in your code.
0
0
Custom error classes in Node.js
Introduction
When you want to clearly identify different error causes in your app.
When you need to add extra information to errors for better debugging.
When you want to handle certain errors differently in your code.
When building libraries or APIs to give users clear error messages.
When you want to keep your error handling organized and readable.
Syntax
Node.js
class MyError extends Error { constructor(message) { super(message); this.name = 'MyError'; } }
Always extend the built-in Error class to keep standard error behavior.
Set the name property to your custom error class name for clear error identification.
Examples
This creates a custom error for validation problems.
Node.js
class ValidationError extends Error { constructor(message) { super(message); this.name = 'ValidationError'; } }
This error class adds a code property to give more details.
Node.js
class DatabaseError extends Error { constructor(message, code) { super(message); this.name = 'DatabaseError'; this.code = code; // extra info } }
Shows how to throw and catch a custom error.
Node.js
try { throw new ValidationError('Invalid input'); } catch (err) { if (err instanceof ValidationError) { console.log('Caught a validation error:', err.message); } }
Sample Program
This program defines a custom error class and uses it to check if input is a number. It doubles the number if valid, or throws a custom error if not. The error is caught and handled gracefully.
Node.js
class CustomError extends Error { constructor(message) { super(message); this.name = 'CustomError'; } } function checkNumber(num) { if (typeof num !== 'number') { throw new CustomError('Not a number!'); } return num * 2; } try { console.log(checkNumber(5)); console.log(checkNumber('hello')); } catch (err) { if (err instanceof CustomError) { console.log(`Custom error caught: ${err.message}`); } else { console.log('Unknown error:', err); } }
OutputSuccess
Important Notes
Always call super(message) in the constructor to set the error message.
Use instanceof to check for your custom error type when catching errors.
Custom errors improve code clarity and debugging experience.
Summary
Custom error classes let you create specific error types for your app.
Extend the built-in Error class and set a custom name.
Use them to handle errors clearly and add extra info if needed.