Spaces:
Sleeping
Sleeping
Download backend/src/middleware/errorHandler.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 6.77 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/middleware/errorHandler.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/middleware/errorHandler.js
-
curl -L -o errorHandler.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/middleware/errorHandler.js
6.77 kB
| 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 | |
| }; |