Spaces:
Sleeping
Sleeping
File size: 6,774 Bytes
7851df6 | 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 264 265 266 267 268 269 270 271 272 273 | const logger = require('../utils/logger');
/**
* Custom error class for API errors
*/
class APIError extends Error {
constructor(message, statusCode = 500, isOperational = true) {
super(message);
this.statusCode = statusCode;
this.isOperational = isOperational;
this.name = 'APIError';
Error.captureStackTrace(this, this.constructor);
}
}
/**
* Custom error class for authentication errors
*/
class AuthenticationError extends APIError {
constructor(message = 'Authentication failed') {
super(message, 401);
this.name = 'AuthenticationError';
}
}
/**
* Custom error class for authorization errors
*/
class AuthorizationError extends APIError {
constructor(message = 'Access denied') {
super(message, 403);
this.name = 'AuthorizationError';
}
}
/**
* Custom error class for validation errors
*/
class ValidationError extends APIError {
constructor(message = 'Validation failed', details = null) {
super(message, 400);
this.name = 'ValidationError';
this.details = details;
}
}
/**
* Custom error class for not found errors
*/
class NotFoundError extends APIError {
constructor(message = 'Resource not found') {
super(message, 404);
this.name = 'NotFoundError';
}
}
/**
* Custom error class for database errors
*/
class DatabaseError extends APIError {
constructor(message = 'Database operation failed') {
super(message, 500);
this.name = 'DatabaseError';
}
}
/**
* Handle different types of errors and convert them to APIError instances
*/
const handleError = (err) => {
// MongoDB/Mongoose errors
if (err.name === 'MongoError' || err.name === 'MongoServerError') {
if (err.code === 11000) {
// Duplicate key error
const field = Object.keys(err.keyPattern)[0];
return new ValidationError(`${field} already exists`, {
field,
value: err.keyValue[field]
});
}
return new DatabaseError(`Database operation failed: ${err.message}`);
}
// Mongoose validation errors
if (err.name === 'ValidationError') {
const details = Object.values(err.errors).map(error => ({
field: error.path,
message: error.message,
value: error.value
}));
return new ValidationError('Validation failed', details);
}
// Mongoose cast errors (invalid ObjectId, etc.)
if (err.name === 'CastError') {
if (err.kind === 'ObjectId') {
return new ValidationError(`Invalid ${err.path} format`);
}
return new ValidationError(`Invalid ${err.path}: ${err.value}`);
}
// JWT errors
if (err.name === 'JsonWebTokenError') {
return new AuthenticationError('Invalid token');
}
if (err.name === 'TokenExpiredError') {
return new AuthenticationError('Token expired');
}
// Multer errors (file upload)
if (err.code === 'LIMIT_FILE_SIZE') {
return new ValidationError('File too large');
}
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
return new ValidationError('Unexpected file field');
}
// Rate limiting errors
if (err.status === 429) {
return new APIError('Rate limit exceeded. Please try again later.', 429);
}
// CORS errors
if (err.message && err.message.includes('CORS')) {
return new APIError('CORS policy violation', 403);
}
// If it's already an API error, return as is
if (err instanceof APIError) {
return err;
}
// Generic error
return new APIError(
process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message,
err.statusCode || 500,
false
);
};
/**
* Main error handling middleware
*/
const errorHandler = (err, req, res, next) => {
const apiError = handleError(err);
const errorId = req.id || Math.random().toString(36).substr(2, 9);
// Log error
const logData = {
errorId,
name: apiError.name,
message: apiError.message,
statusCode: apiError.statusCode,
stack: apiError.stack,
url: req.url,
method: req.method,
ip: req.ip,
userAgent: req.get('User-Agent'),
userId: req.user?.id,
timestamp: new Date().toISOString()
};
// Log level based on error type
if (apiError.statusCode >= 500) {
logger.error('Server error:', logData);
} else if (apiError.statusCode >= 400) {
logger.warn('Client error:', logData);
} else {
logger.info('Request error:', logData);
}
// Prepare response
const response = {
success: false,
error: apiError.message,
errorId,
statusCode: apiError.statusCode
};
// Add details for validation errors
if (apiError instanceof ValidationError && apiError.details) {
response.details = apiError.details;
}
// Add stack trace in development
if (process.env.NODE_ENV === 'development') {
response.stack = apiError.stack;
}
// Add help text for common errors
if (apiError.statusCode === 401) {
response.help = 'Please login and try again';
} else if (apiError.statusCode === 403) {
response.help = 'You do not have permission to perform this action';
} else if (apiError.statusCode === 404) {
response.help = 'The requested resource was not found';
} else if (apiError.statusCode === 429) {
response.help = 'You have exceeded the rate limit. Please wait before trying again';
response.retryAfter = req.rateLimit?.resetTime || 60;
}
res.status(apiError.statusCode).json(response);
};
/**
* Async error wrapper for route handlers
*/
const asyncHandler = (fn) => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
/**
* Handle 404 errors for unmatched routes
*/
const notFoundHandler = (req, res, next) => {
const error = new NotFoundError(`Route ${req.method} ${req.originalUrl} not found`);
next(error);
};
/**
* Handle uncaught promise rejections
*/
const handleUnhandledRejection = (reason, promise) => {
logger.error('Unhandled Promise Rejection:', {
reason: reason?.message || reason,
stack: reason?.stack,
promise: promise.toString()
});
// In development, crash the process to get attention
if (process.env.NODE_ENV === 'development') {
process.exit(1);
}
};
/**
* Handle uncaught exceptions
*/
const handleUncaughtException = (err) => {
logger.error('Uncaught Exception:', {
message: err.message,
stack: err.stack
});
// Always crash on uncaught exceptions
process.exit(1);
};
/**
* Setup global error handlers
*/
const setupGlobalErrorHandlers = () => {
process.on('unhandledRejection', handleUnhandledRejection);
process.on('uncaughtException', handleUncaughtException);
};
module.exports = {
APIError,
AuthenticationError,
AuthorizationError,
ValidationError,
NotFoundError,
DatabaseError,
errorHandler,
asyncHandler,
notFoundHandler,
setupGlobalErrorHandlers
}; |