Centralized Error Handling in Express.js
Express.js application develop করার সময় বিভিন্ন জায়গায় error তৈরি হতে পারে। যেমন: Controller, Service Layer, Database Layer, Authentication Middleware অথবা API Request Processing-এর সময়। প্রতিটি জায়গায় আলাদাভাবে error response পাঠানোর পরিবর্তে আমরা **Centralized Error Handling Middleware** ব্যবহার করতে পারি। এটি application-এর সব error একটি নির্দিষ্ট জায়গায় handle করে এবং consistent API response প্রদান করে।1. What is Centralized Error Handling?
Centralized Error Handling হলো Express.js-এর একটি error management technique, যেখানে application-এর বিভিন্ন layer থেকে আসা error একটি common middleware-এর মাধ্যমে handle করা হয়। এর ফলে প্রতিটি controller-এ আলাদাভাবেres.status().json() লিখে error handle করতে হয় না।
Example:
- Controller Layer: Business logic-related errors.
- Service Layer: Application-level errors.
- Database Layer: PostgreSQL query errors.
- Authentication Layer: Invalid or expired token errors.
- Global Error Middleware: সব error-এর centralized response.
2. Understanding Express Error-Handling Middleware
Express.js-এ একটি standard error-handling middleware-এর চারটি parameter থাকে:function errorHandler(err, req, res, next) {
// Handle application errors
}
এখানে চারটি parameter-এর কাজ:
| Parameter | Description |
|---|---|
err |
যে error তৈরি হয়েছে তার details. |
req |
Incoming HTTP request information. |
res |
Client-কে HTTP response পাঠানোর জন্য. |
next |
পরবর্তী middleware-এ control পাঠানোর জন্য. |
3. How Does It Catch Synchronous Errors?
Synchronous error হলো এমন error যা কোনো synchronous code execute হওয়ার সময় ঘটে। Express.js-এর route handler বা middleware-এর মধ্যে synchronous error throw হলে Express নিজেই সেটি catch করে error-handling middleware-এ পাঠায়। Example:// routes/user.routes.js
const express = require('express');
const router = express.Router();
router.get('/users', (req, res) => {
throw new Error('Something went wrong!');
});
module.exports = router;
এখানে throw new Error() execute হলে Express error-handling middleware-এ error পাঠাবে।
4. How Does It Handle Asynchronous Errors?
Asynchronous error সাধারণত Database Query, API Request, Promise অথবা async/await operation-এর সময় তৈরি হয়। Express 5-এ rejected Promise বা async route handler-এর thrown error automatically error middleware-এ forward হয়। তবে Express 4 ব্যবহার করলে async function-এর error manuallynext(error) দিয়ে forward করতে হবে অথবা async wrapper ব্যবহার করতে হবে।
Express 5 Example:
// controllers/user.controller.js
const getUsers = async (req, res) => {
const users = await User.findAll();
res.status(200).json({
success: true,
data: users
});
};
module.exports = { getUsers };
যদি User.findAll() Promise reject করে, Express 5 সেটি centralized error middleware-এ পাঠাবে।
Express 4 Async Wrapper:
// utils/asyncHandler.js
const asyncHandler = (fn) => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
};
module.exports = asyncHandler;
এখন controller-এ wrapper ব্যবহার করুন:
// controllers/user.controller.js
const asyncHandler = require('../utils/asyncHandler');
const getUsers = asyncHandler(async (req, res) => {
const users = await User.findAll();
res.status(200).json({
success: true,
data: users
});
});
module.exports = { getUsers };
এই wrapper asynchronous error catch করে next(error)-এর মাধ্যমে global error handler-এ পাঠায়।
5. Creating a Custom Application Error
প্রতিটি error-এর জন্য একই HTTP status code ব্যবহার করা উচিত নয়। তাই custom error class তৈরি করে status code এবং error message নির্ধারণ করা যায়। File: utils/AppError.jsclass AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4')
? 'fail'
: 'error';
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = AppError;
এখানে:
message: Error message.statusCode: HTTP status code.status: Error-এর category.isOperational: Expected application error চিহ্নিত করে.captureStackTrace(): Error stack trace তৈরি করে.
6. Creating Centralized Error Handling Middleware
এখন আমাদের মূল centralized error-handling middleware তৈরি করব। File: middleware/error.middleware.jsconst errorHandler = (err, req, res, next) => {
let statusCode = err.statusCode || 500;
let message = err.message || 'Internal Server Error';
// Log error for debugging
console.error(err);
// Prevent sending response twice
if (res.headersSent) {
return next(err);
}
// Production response
if (process.env.NODE_ENV === 'production') {
if (!err.isOperational) {
statusCode = 500;
message = 'Something went wrong!';
}
}
res.status(statusCode).json({
success: false,
status: err.status || 'error',
message: message
});
};
module.exports = errorHandler;
এই middleware কীভাবে কাজ করে?
- Receive Error: বিভিন্ন route, controller অথবা middleware থেকে আসা error receive করে।
- Set Status Code: Error-এর status code নির্ধারণ করে। না থাকলে 500 ব্যবহার করে।
- Log Error: Debugging-এর জন্য server console-এ error log করে।
- Check Headers: Response headers ইতিমধ্যে পাঠানো হয়েছে কি না check করে।
- Hide Internal Details: Production environment-এ unexpected error-এর internal details client-কে প্রকাশ করে না।
- Send Response: Client-কে consistent JSON error response পাঠায়।
7. Using Error Middleware in Express App
Error-handling middleware অবশ্যই application-এর অন্যান্য routes এবং middleware-এর পরে register করতে হবে। File: app.jsconst express = require('express');
const userRoutes = require('./routes/user.routes');
const errorHandler = require('./middleware/error.middleware');
const AppError = require('./utils/AppError');
const app = express();
// Built-in middleware
app.use(express.json());
// API Routes
app.use('/api/users', userRoutes);
// 404 Not Found Handler
app.use((req, res, next) => {
next(new AppError(`Route ${req.originalUrl} not found`, 404));
});
// Centralized Error Handler
app.use(errorHandler);
module.exports = app;
Important: 404 handler-টিও error তৈরি করে next()-এর মাধ্যমে centralized error middleware-এ পাঠাচ্ছে।
8. Throwing Custom Errors from Controller
এখন controller থেকে কীভাবে custom error পাঠানো যায় তা দেখি। File: controllers/user.controller.jsconst AppError = require('../utils/AppError');
const getUserById = async (req, res) => {
const userId = req.params.id;
// Example: User not found
const user = null;
if (!user) {
throw new AppError('User not found', 404);
}
res.status(200).json({
success: true,
data: user
});
};
module.exports = { getUserById };
Express 5-এ এই async controller-এর thrown error automatically error middleware-এ পৌঁছাবে।
Express 4-এ একই controller-কে asyncHandler দিয়ে wrap করতে হবে।
9. Understanding the Complete Error Flow
আমাদের layered architecture-এ error handling-এর flow সাধারণত এমন:Client Request
|
v
Express Router
|
v
Controller Layer
|
v
Service Layer
|
v
Database Layer
|
v
Error Occurs
|
v
next(error) / Express 5 Promise Handling
|
v
Centralized Error Middleware
|
v
JSON Error Response
|
v
Client
Example API Response:
যদি user পাওয়া না যায়, তাহলে response হবে:
{
"success": false,
"status": "fail",
"message": "User not found"
}
HTTP Status Code: 404 Not Found
10. Common HTTP Error Status Codes
| Status Code | Meaning | Example |
|---|---|---|
| 400 | Bad Request | Invalid request data |
| 401 | Unauthorized | Missing or invalid token |
| 403 | Forbidden | User has no permission |
| 404 | Not Found | User or resource not found |
| 409 | Conflict | Email already exists |
| 422 | Unprocessable Entity | Validation failed |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server error |
11. Best Practices for Centralized Error Handling
- Always use one centralized error-handling middleware.
- Use custom error classes for operational errors.
- Use appropriate HTTP status codes.
- Handle asynchronous errors correctly according to your Express version.
- Never expose database credentials, SQL queries, stack traces or sensitive information to clients.
- Log unexpected errors for debugging and monitoring.
- Use environment variables to separate development and production behavior.
- Always register the global error middleware after routes and the 404 handler.
- Do not send multiple responses for the same request.
12. Frequently Asked Questions (FAQ)
What is centralized error handling in Express.js?
It is a technique where application errors are forwarded to one global error-handling middleware instead of handling them separately in every route or controller.
Why does Express error middleware require four parameters?
Express identifies an error-handling middleware by its four-parameter signature: (err, req, res, next).
Does Express automatically catch asynchronous errors?
Express 5 automatically forwards rejected Promises from route handlers and middleware. In Express 4, you need to forward asynchronous errors using next(error) or an async wrapper.
What is the difference between next() and next(error)?
next() moves control to the next regular middleware, whereas next(error) forwards the error to an error-handling middleware.
Where should error middleware be registered?
Register it after all application routes and the 404 handler so that errors forwarded by earlier middleware can reach it.
13. Practical Assignment
এখন নিজের Express.js project-এ নিচের tasks complete করার চেষ্টা করুন:- Create a custom
AppErrorclass. - Create a centralized error-handling middleware.
- Create a custom 404 Not Found handler.
- Handle synchronous errors using
throw new Error(). - Handle asynchronous errors using Express 5 অথবা Express 4 async wrapper.
- Test your API using Postman.
- Return consistent JSON error responses.
Centralized Error Handling makes your Express.js application more maintainable, secure and easier to debug. Instead of handling errors everywhere, forward them to one global middleware and manage them consistently.
Express.js Backend Development