4 min read
•Question 26 of 62mediumWhat are the types of errors in Node.js?
Understanding different error types and handling strategies.
What You'll Learn
- Types of errors in Node.js
- How to handle each type
- Best practices
Error Types
1. Standard JavaScript Errors
code.jsJavaScript
// SyntaxError, TypeError, ReferenceError, RangeError
throw new TypeError('Expected string');
throw new RangeError('Index out of bounds');2. System Errors
code.jsJavaScript
// OS-level errors
const fs = require('fs');
fs.readFile('/nonexistent', (err, data) => {
if (err) {
console.log(err.code); // 'ENOENT'
console.log(err.syscall); // 'open'
console.log(err.path); // '/nonexistent'
}
});Common system error codes:
ENOENT- File/directory not foundEACCES- Permission deniedECONNREFUSED- Connection refusedETIMEDOUT- Operation timed out
3. Custom Application Errors
code.jsJavaScript
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
class NotFoundError extends AppError {
constructor(message = 'Resource not found') {
super(message, 404);
}
}
// Usage
throw new NotFoundError('User not found');Handling Uncaught Errors
code.jsJavaScript
// Uncaught exceptions
process.on('uncaughtException', (err) => {
console.error('Uncaught:', err);
process.exit(1);
});
// Unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
});