/** * Error Handling Middleware * Centralized error handling with security considerations */ import winston from 'winston'; // Logger for errors const errorLogger = winston.createLogger({ level: 'error', format: winston.format.combine( winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json() ), transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.simple() ) }), new winston.transports.File({ filename: 'logs/errors.log', maxsize: 5242880, // 5MB maxFiles: 5 }) ] }); // Custom error classes export class AppError extends Error { constructor(message, statusCode, code = null) { super(message); this.statusCode = statusCode; this.code = code; this.isOperational = true; Error.captureStackTrace(this, this.constructor); } } export class ValidationError extends AppError { constructor(message, errors = []) { super(message, 400, 'VALIDATION_ERROR'); this.errors = errors; } } export class AuthenticationError extends AppError { constructor(message = 'Authentication failed') { super(message, 401, 'AUTHENTICATION_ERROR'); } } export class AuthorizationError extends AppError { constructor(message = 'Access denied') { super(message, 403, 'AUTHORIZATION_ERROR'); } } export class NotFoundError extends AppError { constructor(message = 'Resource not found') { super(message, 404, 'NOT_FOUND'); } } export class ConflictError extends AppError { constructor(message = 'Resource already exists') { super(message, 409, 'CONFLICT'); } } export class RateLimitError extends AppError { constructor(message = 'Too many requests') { super(message, 429, 'RATE_LIMIT'); } } // Sensitive error messages that should not be exposed const SENSITIVE_PATTERNS = [ /password/i, /secret/i, /token/i, /key/i, /credential/i, /auth/i, /sql/i, /database/i, /connection/i, /timeout/i ]; // Sanitize error message for client const sanitizeErrorMessage = (message, statusCode) => { // In production, don't expose internal error details if (process.env.NODE_ENV === 'production') { // For server errors, return generic message if (statusCode >= 500) { return 'An unexpected error occurred. Please try again later.'; } // Check if message contains sensitive info if (SENSITIVE_PATTERNS.some(pattern => pattern.test(message))) { return 'An error occurred. Please check your input and try again.'; } } return message; }; // Main error handler middleware export const errorHandler = (err, req, res, next) => { let error = { ...err }; error.message = err.message; // Log error const errorData = { message: err.message, stack: err.stack, statusCode: err.statusCode || 500, code: err.code, path: req.path, method: req.method, ip: req.ip, userAgent: req.headers['user-agent'], userId: req.user?.id, requestId: req.id, timestamp: new Date().toISOString() }; // Don't log stack trace in production for 4xx errors if (process.env.NODE_ENV === 'production' && err.statusCode < 500) { delete errorData.stack; } errorLogger.error('Error occurred', errorData); // Handle specific error types // JWT errors if (err.name === 'JsonWebTokenError') { return res.status(401).json({ success: false, message: 'Invalid token', code: 'INVALID_TOKEN' }); } if (err.name === 'TokenExpiredError') { return res.status(401).json({ success: false, message: 'Token expired', code: 'TOKEN_EXPIRED' }); } // Validation errors if (err.name === 'ValidationError') { return res.status(400).json({ success: false, message: 'Validation failed', code: 'VALIDATION_ERROR', errors: err.errors || [{ message: err.message }] }); } // MongoDB errors if (err.name === 'CastError') { return res.status(400).json({ success: false, message: 'Invalid ID format', code: 'INVALID_ID' }); } if (err.code === 11000) { const field = Object.keys(err.keyValue)[0]; return res.status(409).json({ success: false, message: `${field} already exists`, code: 'DUPLICATE_ERROR' }); } // Syntax errors (malformed JSON) if (err instanceof SyntaxError && err.status === 400 && 'body' in err) { return res.status(400).json({ success: false, message: 'Invalid JSON format', code: 'INVALID_JSON' }); } // CORS errors if (err.message === 'Not allowed by CORS') { return res.status(403).json({ success: false, message: 'Cross-origin request blocked', code: 'CORS_ERROR' }); } // Default error response const statusCode = err.statusCode || 500; const code = err.code || 'INTERNAL_ERROR'; const message = sanitizeErrorMessage(err.message, statusCode); const response = { success: false, message, code }; // Include errors array for validation errors if (err.errors && Array.isArray(err.errors)) { response.errors = err.errors; } // Include stack trace in development if (process.env.NODE_ENV === 'development' && err.stack) { response.stack = err.stack.split('\n').slice(0, 5); } res.status(statusCode).json(response); }; // Async handler wrapper export const asyncHandler = (fn) => { return (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; }; // 404 Not Found handler export const notFound = (req, res, next) => { const error = new NotFoundError(`Route not found: ${req.method} ${req.path}`); next(error); }; // Uncaught exception handler export const handleUncaughtException = (err) => { errorLogger.error('UNCAUGHT EXCEPTION', { message: err.message, stack: err.stack }); // Graceful shutdown setTimeout(() => { process.exit(1); }, 1000); }; // Unhandled rejection handler export const handleUnhandledRejection = (reason, promise) => { errorLogger.error('UNHANDLED REJECTION', { reason: reason?.message || reason, stack: reason?.stack }); }; export default errorHandler;