/** * Error Handler Middleware * Sanitizes errors before sending to client (security best practice) */ function errorHandler(err, req, res, _next) { // Log full error internally (with stack trace) console.error('[ERROR]', { timestamp: new Date().toISOString(), path: req.path, method: req.method, error: err.message, code: err.code, stack: process.env.NODE_ENV !== 'production' ? err.stack : undefined, }); // Determine error type const statusCode = err.statusCode || 500; const isClientError = statusCode >= 400 && statusCode < 500; // Send sanitized response to client // IMPORTANT: Never expose internal error messages in production res.status(statusCode).json({ success: false, error: isClientError ? err.message : 'Internal server error', code: err.code || 'INTERNAL_ERROR', }); } module.exports = { errorHandler };