Step 1: Create the Error Handler Middleware
// errorHandler.js
const errorHandler = (err, req, res, next) => {
const statusCode = err.statusCode || 500;
const message = err.message || 'Internal Server Error';
res.status(statusCode).json({
success: false,
status: statusCode,
message: message,
stack: process.env.NODE_ENV === 'development' ? err.stack : null,
});
};
module.exports = errorHandler;
Step 2: Use the Error Handler in Your App
// app.js
const express = require('express');
const app = express();
const errorHandler = require('./errorHandler');
// ... your routes and other middleware
// Error handler middleware (must be added last)
app.use(errorHandler);