Error Handling in Express.js
✅ Error Handling in Express.js (English)
Error handling is a crucial part of building reliable and secure applications in Express.js. Here's a guide to effectively handling errors in an Express.js app.
๐งฑ 1. Basic Error Handling Middleware
Express allows you to define error-handling middleware by providing a function with four arguments: (err, req, res, next).
js
Copy
Edit
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});
This middleware catches any error passed using next(err) or thrown in async code wrapped correctly.
๐ 2. Catching Errors in Routes
You can handle errors inside route handlers and forward them to the error-handling middleware:
js
Copy
Edit
app.get('/user/:id', (req, res, next) => {
try {
// Simulate error
throw new Error('User not found');
} catch (err) {
next(err); // Pass error to error-handling middleware
}
});
⏳ 3. Handling Async Errors (with Async/Await)
For async functions, you need to catch errors and pass them to next() manually or use a helper.
js
Copy
Edit
app.get('/async-data', async (req, res, next) => {
try {
const data = await fetchData();
res.json(data);
} catch (err) {
next(err);
}
});
๐ง Optional: Helper to wrap async functions
js
Copy
Edit
const asyncHandler = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
// Usage
app.get('/products', asyncHandler(async (req, res) => {
const products = await getProducts();
res.json(products);
}));
๐งช 4. Custom Error Classes (Optional, but Recommended)
Create custom error types to distinguish between different kinds of errors:
js
Copy
Edit
class NotFoundError extends Error {
constructor(message) {
super(message);
this.statusCode = 404;
}
}
Use it like this:
js
Copy
Edit
app.get('/item/:id', (req, res, next) => {
const item = null; // Assume not found
if (!item) {
return next(new NotFoundError('Item not found'));
}
});
Update your error middleware to handle different types:
js
Copy
Edit
app.use((err, req, res, next) => {
const status = err.statusCode || 500;
res.status(status).json({
error: {
message: err.message || 'Internal Server Error',
}
});
});
๐จ 5. Common Error Types to Handle
400 – Bad Request (e.g., validation error)
401 – Unauthorized
403 – Forbidden
404 – Not Found
500 – Internal Server Error
๐ฆ 6. Using Validation Libraries (Optional)
You can use tools like Joi or express-validator to validate input and handle errors more cleanly.
๐งฏ 7. Global Error Handling Tips
Always log critical errors (console.error, or with logging libraries like winston).
Don’t leak stack traces or internal details in production.
Handle both synchronous and asynchronous errors.
Use centralized error handling for consistency.
Learn MERN Stack Course in Hyderabad
Read More
Building a Pagination API with MongoDB
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment