UNPKG

thrilled-be-core

Version:

Core Express backend package with middleware, logging, security, and base application setup

159 lines 4.84 kB
/** * Enhanced Error Middleware for Enterprise Applications * * This middleware provides comprehensive error handling using custom error classes. * It includes proper error logging, response formatting, correlation ID tracking, * error classification, and development vs production error handling strategies. * * @package be-core * @since 1.0.0 */ import { Request, Response, NextFunction } from 'express'; import { Logger } from '../logging/Logger'; export { AppError, ErrorUtils, DatabaseError, ValidationError, AuthenticationError, AuthorizationError, NotFoundError, ConflictError, RateLimitError, ExternalServiceError, RequestTimeoutError, } from '../utils/errors'; export interface EnhancedErrorMiddlewareOptions { logger?: Logger; includeStack?: boolean; logLevel?: 'error' | 'warn' | 'info' | 'debug'; trustProxy?: boolean; correlationIdProperty?: string; } /** * Enhanced Error Middleware with correlation ID tracking and comprehensive error context */ export declare class EnhancedErrorMiddleware { private logger; private options; constructor(options?: EnhancedErrorMiddlewareOptions); /** * Main error handler middleware */ handle(): (error: unknown, req: Request, res: Response, next: NextFunction) => void; /** * 404 Not Found handler with enhanced debugging information */ notFound(): (req: Request, res: Response) => void; /** * Get available routes from Express app */ private getAvailableRoutes; /** * Recursively extract routes from Express router stack */ private extractRoutesFromStack; /** * Send enhanced 404 response with available routes in development */ private sendNotFoundResponse; /** * Suggest similar routes based on the requested route */ private suggestSimilarRoute; /** * Calculate simple similarity between two strings */ private calculateSimilarity; /** * Calculate edit distance between two strings */ private calculateEditDistance; /** * Log error with enriched context */ private logError; /** * Send error response with proper formatting */ private sendErrorResponse; /** * Handle validation errors */ private handleValidationError; /** * Handle authentication/authorization errors */ private handleAuthError; /** * Handle rate limit errors */ private handleRateLimitError; /** * Handle database errors */ private handleDatabaseError; /** * Handle external service errors */ private handleExternalServiceError; /** * Send fallback response when error handler fails */ private sendFallbackResponse; /** * Get request ID from correlation ID or headers */ private getRequestId; /** * Get user ID from request */ private getUserId; /** * Get session ID from request */ private getSessionId; /** * Get client IP address */ private getClientIP; /** * Sanitize request headers for logging */ private sanitizeHeaders; /** * Sanitize request body for logging */ private sanitizeBody; /** * Classify error type for monitoring and alerting */ private classifyError; /** * Determine error severity for alerting */ private determineSeverity; /** * Categorize error for monitoring dashboards */ private categorizeError; /** * Determine if error should trigger notifications */ private shouldNotifyError; /** * Health check for error middleware */ healthCheck(): { name: string; status: "healthy"; timestamp: string; details: { includeStack: boolean; logLevel: "info" | "error" | "warn" | "debug"; trustProxy: boolean; correlationIdProperty: string; }; }; } /** * Factory function to create error middleware instance */ export declare function createEnhancedErrorMiddleware(options?: EnhancedErrorMiddlewareOptions): EnhancedErrorMiddleware; /** * Express async handler wrapper */ export declare function asyncHandler<T extends unknown[]>(fn: (req: Request, res: Response, next: NextFunction, ...args: T) => Promise<void>): (req: Request, res: Response, next: NextFunction, ...args: T) => void; /** * Error boundary for specific route handlers */ export declare function errorBoundary<T extends unknown[]>(fn: (req: Request, res: Response, next: NextFunction, ...args: T) => Promise<void>, errorHandler?: (error: any, req: Request, res: Response) => void): (req: Request, res: Response, next: NextFunction, ...args: T) => Promise<void>; //# sourceMappingURL=EnhancedErrorMiddleware.d.ts.map