Proper error handling is crucial for building stable and reliable Node.js applications. This guide covers best practices for handling both synchronous and asynchronous errors.
Synchronous Errors: `try...catch`
For synchronous code, the standard `try...catch` block is the way to go.
try {
const data = JSON.parse(invalidJsonString);
} catch (error) {
console.error('Failed to parse JSON:', error);
}
Asynchronous Errors: Promises and `async/await`
For Promises, you can chain a `.catch()` block. With `async/await`, you can use `try...catch` just like with synchronous code.
// async/await
app.get('/data', async (req, res) => {
try {
const data = await fetchDataFromDb();
res.json(data);
} catch (error) {
res.status(500).send('Database error');
}
});
Centralized Error Handling in Express
The best practice in an Express application is to create a centralized error-handling middleware. This middleware is defined with four arguments `(err, req, res, next)`.
// This middleware should be the last one in your app.use() stack
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Comments
Post a Comment