Proper error and exception handling is critical for building stable Node.js applications. Here’s how you can handle errors effectively:
1. Use Try-Catch for Synchronous Code
- Useful for code that doesn’t use callbacks or Promises.
- Example:
try {
// Synchronous code that may throw
let data = fs.readFileSync('file.txt');
} catch (err) {
console.error('Error reading file:', err);
}
2. Handle Errors in Callbacks
- Always check for the first
errargument in callbacks. - Example:
fs.readFile('file.txt', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('File data:', data);
});
3. Manage Promises and Async/Await Errors
- Use
.catch()for Promises and try-catch for async functions. - Example:
// Promise
readFileAsync('file.txt')
.then(data => console.log(data))
.catch(err => console.error('Promise error:', err));
// Async/Await
async function readFile() {
try {
let data = await readFileAsync('file.txt');
console.log(data);
} catch (err) {
console.error('Async/Await error:', err);
}
}
4. Handle Uncaught Exceptions and Unhandled Rejections
- Use process events to log and shut down gracefully.
- Example:
process.on('uncaughtException', err => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', reason => {
console.error('Unhandled Rejection:', reason);
process.exit(1);
});
5. Use Error Middleware in Express
- Handle errors efficiently in web APIs.
- Example:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Summary: Always handle errors at every layer—synchronous, callback, promise, and process level. This keeps your Node.js applications resilient and maintainable.
Top comments (0)