File size: 6,293 Bytes
6711fd5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | /**
* 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;
|