qapinterface
Version:
Comprehensive API utilities for Node.js applications including authentication, security, request processing, and response handling with zero external dependencies
38 lines (33 loc) • 980 B
JavaScript
/**
* Error Handling Middleware
* Single Responsibility: Generic Express error handling middleware
*/
const { logger } = require('../asyncLogger');
const { createErrorResponse } = require('./error-response-creator');
/**
* A generic error handling middleware for Express.
* This should be the last middleware added to the app.
* @param {Error} err - The error object.
* @param {object} req - The Express request object.
* @param {object} res - The Express response object.
* @param {function} next - The Express next function.
*/
function errorHandlerMiddleware(err, req, res, next) {
// Log the error with request context
logger.error({
err,
req: {
id: req.id,
method: req.method,
url: req.originalUrl,
ip: req.ip,
}
}, 'An unexpected error occurred');
if (res.headersSent) {
return next(err);
}
res.status(500).json(createErrorResponse('Internal Server Error'));
}
module.exports = {
errorHandlerMiddleware
};