Node.js — Error Handling
Try-Catch
try {
const data = JSON.parse(invalidJson);
} catch (error) {
console.error('Parse error:', error.message);
}
Error Types
| Type | Description |
|---|---|
| Error | Base error class |
| TypeError | Wrong type |
| ReferenceError | Undefined variable |
| SyntaxError | Invalid syntax |
| RangeError | Out of range |
Custom Errors
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
throw new ValidationError('Invalid email', 'email');
Error Handling Patterns
// Callback
function fetchData(callback) {
fs.readFile('data.json', (err, data) => {
if (err) return callback(err);
callback(null, JSON.parse(data));
});
}
// Promise
function fetchData() {
return fs.promises.readFile('data.json')
.then(data => JSON.parse(data));
}
// Async/Await
async function fetchData() {
try {
const data = await fs.promises.readFile('data.json');
return JSON.parse(data);
} catch (error) {
console.error('Error:', error.message);
throw error;
}
}
Uncaught Exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection:', reason);
});
Mini Practice
- Use try-catch
- Create custom error classes
- Handle async errors
- Add global error handlers
Up Next
Continue with Debugging — debugging Node.js applications.
Related Topics
Frequently Asked Questions about Error Handling
What is Error Handling in Node.js?
Error Handling is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Error Handling?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Error Handling.
Why is Error Handling important in Node.js?
Error Handling is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.