gCore

ErrorManager Documentation

Overview

The ErrorManager provides error handling, logging, tracking, and notification capabilities for the gCore framework. It enables perfect domain isolation with zero-coordination scaling across distributed systems, while maintaining high performance and reliability even in failure scenarios.

Key Features

Architecture

The ErrorManager follows gCore's modular trait-based architecture:

Core Components

Traits

Integration with gCore

Getting Started

Basic Usage

// Get ErrorManager instance
$errorManager = gcore_get_error_manager();

// Track simple error
$errorManager->trackError('connection_failed', [
    'service' => 'database',
    'host' => 'db.example.com',
    'latency' => 1250
]);

// Log error with severity
$errorManager->logError(
    'validation_failed',
    [
        'form' => 'registration',
        'field' => 'email',
        'value' => $sanitizedEmail
    ],
    LOG_WARNING, // Severity level
    'VALIDATION' // Error category
);

// Send notifications
$errorManager->notify(
    'security_breach',
    [
        'user_id' => $userId,
        'ip' => $requestIp,
        'attempt_count' => $attempts
    ],
    ['email', 'slack'] // Notification channels
);

// Register global error handlers
$errorManager->registerErrorHandler();
$errorManager->registerExceptionHandler();
$errorManager->registerShutdownHandler();

Error Context Collection

The ErrorManager automatically collects rich context for errors:

try {
    // Potentially failing code
    processSomething();
} catch (\Exception $e) {
    // Log exception with automatic context collection
    $errorManager->logException($e, [
        'operation' => 'data_processing',
        'custom_context' => 'Additional information'
    ]);
}

The collected context includes:

Advanced Features

Multi-Channel Notifications

Configure and use multiple notification channels:

// Initialize notification channels
$errorManager->setupNotificationChannels([
    'email' => [
        'recipients' => ['admin@example.com', 'ops@example.com'],
        'threshold' => 'WARNING' // Minimum level to notify
    ],
    'slack' => [
        'webhook' => 'https://hooks.slack.com/services/XXX/YYY/ZZZ',
        'channel' => '#alerts',
        'threshold' => 'ERROR'
    ],
    'sms' => [
        'numbers' => ['+1234567890'],
        'threshold' => 'CRITICAL',
        'rate_limit' => ['max' => 5, 'period' => 3600] // Max 5 per hour
    ]
]);

// Send to specific channel
$errorManager->notifyChannel('slack', 'Database connection failed', [
    'server' => 'db-primary',
    'error' => 'Connection timeout'
]);

// Notify administrators
$errorManager->notifyAdmin(
    'Critical system error',
    ['error' => 'Memory limit exceeded'],
    ['urgent' => true] // Options
);

// Send to all channels (respecting thresholds)
$errorManager->notifyAll(
    'System restart required',
    ['reason' => 'Scheduled maintenance']
);

Automated Error Recovery

Implement automatic recovery strategies for known errors:

// Register recovery script for specific error
$errorManager->registerErrorScript('connection_failed', '
    // Reset connection pool
    $pool = gcore_get_cache_manager()->getConnectionPool();
    $pool->clearPool();

    // Try to establish new connection
    return $pool->getConnection() !== null;
');

// Attempt recovery
if ($errorManager->isRecoverable('connection_failed')) {
    $success = $errorManager->attemptRecovery('connection_failed', [
        'service' => 'database'
    ]);

    if ($success) {
        // Recovery succeeded, continue operation
    } else {
        // Recovery failed, fallback to plan B
    }
}

Error Pattern Analysis

Analyze error patterns to identify systemic issues:

// Get error frequency
$frequency = $errorManager->getErrorFrequency('api_timeout', 3600); // Last hour

// Analyze error patterns
$patterns = $errorManager->analyzeErrorPattern('validation_failed', 86400); // Last day

// Get most frequent errors
$topErrors = $errorManager->getTopErrors(10, 86400); // Top 10 in last day

Self-Contained Error Handling

Use the standalone error handler for framework initialization and dependency-free operation:

// Get standalone error handler
$handler = \gCore\Modules\Core\Utils\SelfContainedErrorHandler::getInstance();

// Initialize with options
$handler->initialize([
    'log_path' => '/var/log/my-app/errors.log',
    'capture_stacktrace' => true,
    'log_level' => LOG_WARNING
]);

// Register as global handler
$handler->register();

try {
    // Critical initialization code
    initializeFramework();
} catch (\Throwable $e) {
    // Handle initialization failure
    $handler->handleException($e);
    exit(1);
}

API Digest

Main ErrorManager Class

AdvancedLoggingTrait

NotificationTrait

ScriptHandlingTrait

SelfContainedErrorHandler

Domain Isolation and Scaling

The ErrorManager ensures perfect isolation in multi-tenant environments:

// Site-specific key generation ensures proper isolation
private function buildStateKey(string $type, ?string $subKey = null): string
{
    $key = sprintf(
        '{%s}:node:%s:errors:%s',
        $this->siteId,
        $this->nodeId,
        $type
    );

    if ($subKey !== null) {
        $key .= ':' . $subKey;
    }

    return $key;
}

This design enables:

  1. Zero-Coordination Scaling: Multiple nodes operate independently
  2. Perfect Domain Isolation: Errors from one tenant never leak to another
  3. Shared Infrastructure: All tenants use the same ValKey/Redis backend
  4. Hierarchical Aggregation: Cross-site metrics with proper isolation

Error Stream Processing

High-throughput error processing with backpressure control:

// Error processing happens through queues, not direct handling
$errorManager->processErrorQueue(100); // Process up to 100 errors

// Stream-based error processing provides backpressure
$errorId = $valKey->xadd(
    $this->buildStateKey('stream'),
    '*', // Auto-generate ID
    [
        'code' => $errorCode,
        'context' => $this->serializeContext($context),
        'time' => microtime(true),
        'level' => $level
    ]
);

// Automatic stream trimming prevents unbounded growth
$valKey->xtrim(
    $this->buildStateKey('stream'),
    'MAXLEN', 
    '~', // Approximate trimming for performance
    $this->config['max_error_stream_size'] ?? 10000
);

Performance Optimization

Optimized for high-throughput error handling:

  1. Batch Processing: Process multiple errors in batches
  2. Deferred Handling: Non-critical errors are processed asynchronously
  3. Rate Limiting: Throttling for high-frequency errors
  4. Stream-Based Architecture: Efficient error queueing
  5. Context Sampling: Selective context for high-volume errors
// Rate limiting prevents error storms
if ($this->isRateLimited($errorCode)) {
    // Track but don't process fully
    $this->incrementCounter('rate_limited', 1);
    return false;
}

// Context sampling reduces storage for high-volume errors
$sampleRate = $this->getSampleRate($errorCode);
if (rand(1, 100) > $sampleRate) {
    // Store minimal context
    $context = ['sampled' => true];
}

Integration with Other Managers

The ErrorManager integrates with:

  1. CacheManager: For distributed error storage
  2. SecurityManager: For security-related events
  3. APIManager: For API error handling

It's also designed to function independently during initialization to avoid circular dependencies.

Best Practices

  1. Use Domain-Specific Error Codes

    • Create meaningful error codes
    • Use prefix for subsystems (DB, API, AUTH_)
    • Include error type in code (NOT_FOUND, TIMEOUT)
  2. Provide Rich Context

    • Include relevant data for diagnosis
    • Avoid sensitive information (credentials, personal data)
    • Use sanitized values for context
  3. Set Appropriate Severity Levels

    • Use LOG_DEBUG for verbose information
    • Use LOG_INFO for normal operations
    • Use LOG_WARNING for concerning but non-critical issues
    • Use LOG_ERROR for failures requiring attention
    • Use LOG_CRITICAL for system-threatening issues
  4. Configure Notification Channels Wisely

    • Set appropriate thresholds for each channel
    • Use rate limiting to prevent notification fatigue
    • Include sufficient context for action
  5. Monitor Error Patterns

    • Track error frequency and patterns
    • Set up alerts for abnormal error rates
    • Analyze for correlations between errors

Troubleshooting

Common Issues

  1. High Error Volumes

    • Implement rate limiting
    • Use sampling for high-frequency errors
    • Check for loops generating errors
  2. Missing Context

    • Ensure context is provided with all error calls
    • Verify context serialization works correctly
    • Check context size limits
  3. Notification Failures

    • Verify notification channel configuration
    • Check rate limiting status
    • Ensure notification handlers are working
  4. Performance Issues

    • Use batch processing for errors
    • Implement appropriate sampling
    • Optimize context size

Conclusion

The ErrorManager provides error handling, logging, and notification capabilities for gCore applications. Its domain isolation, stream-based architecture, and multi-channel notifications make it ideal for distributed, multi-tenant environments where reliability and performance are critical.


Updated: March 2025