Error Handling & Resilience
Relevant source files
The following files were used as context for generating this wiki page:
The MarketSage platform implements a robust error handling and resilience framework designed to manage failures gracefully across its distributed components. The system utilizes a centralized error management pattern, combining structured error reporting, automated remediation strategies, and real-time monitoring to ensure platform stability during interactions with external marketplaces.
At its core, the architecture relies on a singleton ErrorHandler that classifies issues by severity and category. This allows the system to differentiate between minor UI glitches and critical security or storage failures, triggering appropriate recovery actions like state resets or rate-limit adjustments automatically.
Centralized Error Management
The primary mechanism for managing exceptions is the ErrorHandler class. It provides a unified interface for catching, reporting, and reacting to both standard JavaScript errors and specialized application errors.
Error Classification
Errors are categorized to allow for granular handling logic. The system defines specific levels of severity and functional categories to guide the remediation process.
| Level / Category | Type | Description |
|---|---|---|
| Severity | LOW | Minor issues that do not disrupt core functionality. |
| Severity | MEDIUM | Issues requiring attention but not immediately fatal. |
| Severity | HIGH | Serious failures affecting significant features. |
| Severity | CRITICAL | Fatal errors requiring immediate remediation (e.g., state reset). |
| Category | NETWORK | Failures related to API calls or external marketplace connectivity. |
| Category | STORAGE | Issues with local storage or state persistence. |
| Category | SECURITY | Validation failures or potential threat detections. |
| Category | ANALYSIS | Errors occurring during AI or data processing tasks. |
Sources: src/common/errors/ErrorHandler.ts:5-28, src/core/error/ErrorHandler.ts:1-10
The AppError Class
Custom metadata is attached to exceptions via the AppError (or CustomError) class, which extends the base Error. This includes a unique error code, severity level, category, and an optional context object for debugging.
export class AppError extends Error {
constructor(
message: string,
public code: string,
public severity: ErrorSeverity,
public category: ErrorCategory,
public context?: Record<string, any>
) {
super(message);
this.name = 'AppError';
Object.setPrototypeOf(this, AppError.prototype);
}
}
Sources: src/common/errors/ErrorHandler.ts:33-45
Architectural Flow
The error handling flow follows a reporter-subscriber pattern where errors are logged, metrics are updated, and then dispatched to various reporting services (like the console or analytics) before remediation is attempted.
Error Processing Pipeline
The following diagram illustrates how an error moves through the system from detection to remediation.
The ErrorHandler updates internal metrics every time an error is handled, allowing for real-time monitoring of error rates.
Sources: src/common/errors/ErrorHandler.ts:98-124, src/core/error/ErrorHandler.ts:14-35
Resilience Strategies
MarketSage employs several patterns to maintain operation during intermittent failures or unexpected data states.
Automated Remediation
The system performs "self-healing" actions based on the error category when a CRITICAL severity is reached. For example, if a STORAGE error is detected, the ErrorHandler attempts to reset the StateManager to clear corrupted data. In the core implementation, specific codes like RATE_LIMIT_EXCEEDED trigger adjustments in the RateLimiter.
Sources: src/common/errors/ErrorHandler.ts:143-165, src/core/error/ErrorHandler.ts:54-65
Resilient Platform Handlers
External marketplace interactions (Temu, AliExpress, DHGate) include built-in resilience using retry logic and input validation. The BasePlatformHandler implements an exponential backoff strategy for preparing checkout URLs.
for (let attempt = 1; attempt <= this.RETRY_ATTEMPTS; attempt++) {
try {
// Attempt operation...
return url;
} catch (error) {
if (attempt === this.RETRY_ATTEMPTS) throw error;
await this.delay(this.RETRY_DELAY * Math.pow(2, attempt - 1));
}
}
Sources: src/services/checkout/PlatformHandlers.ts:74-85
Async Error Handling
High-level services, such as SocialCommerceAnalytics, use decorators like @AsyncErrorHandler() to wrap asynchronous operations. This ensures that background tasks (e.g., real-time metric collection) do not crash the service if a single interval fails.
Sources: src/core/social/SocialCommerceAnalytics.ts:405-412, src/core/monitoring/MarketplaceMonitoringDashboard.ts:219-223
Monitoring and Metrics
Resilience is supported by a monitoring layer that tracks error health across the application.
Error Metrics Tracking
The ErrorHandler maintains a Map<string, number> of error codes. If the error rate for a specific code exceeds a threshold defined in AppConfig, an alert is triggered.
Dashboard Integration
The MarketplaceMonitoringDashboard provides visibility into the system's error state. It calculates a systemHealth metric based on the current error rate and response times, categorized as good, warning, or critical.
| Metric | Threshold | Action |
|---|---|---|
errorRate | > 0.05 (5%) | System status moves to warning |
errorRate | > 0.10 (10%) | System status moves to critical |
responseTime | > 3000ms | Trigger Performance Alert |
Sources: src/core/monitoring/MarketplaceMonitoringDashboard.ts:192-198, src/core/monitoring/MarketplaceMonitoringDashboard.ts:503-511
Conclusion
Error handling in MarketSage is not merely a logging mechanism but an active resilience system. By categorizing errors and linking them to automated remediation actions—such as state resets for storage failures or exponential backoff for network requests—the platform maintains high availability even when encountering the unpredictable nature of external e-commerce data and network environments. Professional monitoring via the dashboard ensures that developers can respond to trends before they impact the end-user experience.