Error handling in Express.js is essential for building reliable and user-friendly APIs. Express provides a built-in way to handle errors gracefully and send meaningful responses to the client.
Basics of Error Handling in Express.js
1. Use Express's Error-Handling Middleware
Express error-handling middleware is defined by a function with four arguments:
(err, req, res, next).
app.use((err, req, res, next) => {
console.error(err.stack); // log the error for debugging
res.status(err.status || 500).json({
success: false,
message: err.message || 'Internal Server Error',
});
});
2. Throwing Errors in Routes or Controllers
app.get('/api/user/:id', async (req, res, next) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
const error = new Error('User not found');
error.status = 404;
throw error;
}
res.json({ success: true, data: user });
} catch (err) {
next(err); // Pass the error to the error-handling middleware
}
});
Create a Reusable Error Class (Optional but Recommended)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Error handling in Express.js is essential for building reliable and user-friendly APIs. Express provides a built-in way to handle errors gracefully and send meaningful responses to the client.
Basics of Error Handling in Express.js
1. Use Express's Error-Handling Middleware
Express error-handling middleware is defined by a function with four arguments:
(err, req, res, next).2. Throwing Errors in Routes or Controllers
Create a Reusable Error Class (Optional but Recommended)
Use it like this:
Catch Async Errors with a Wrapper
Tips for Better Error Handling
{ success: false, message, code, etc. }express-validatorand return validation-specific errors.express-async-handler.