Skip to content

Latest commit

 

History

History
113 lines (90 loc) · 2.56 KB

File metadata and controls

113 lines (90 loc) · 2.56 KB

Retry Logic

Build robust retry mechanisms using PDOdb exception handling.

Basic Retry Pattern

Simple Retry Function

function executeWithRetry(callable $operation, int $maxRetries = 3): mixed
{
    $attempt = 0;
    $lastException = null;
    
    while ($attempt < $maxRetries) {
        try {
            return $operation();
        } catch (ConnectionException $e) {
            $lastException = $e;
            $attempt++;
            
            if ($attempt < $maxRetries) {
                sleep(2 ** $attempt);  // Exponential backoff
            }
        } catch (\Exception $e) {
            // Don't retry on non-retryable errors
            throw $e;
        }
    }
    
    throw $lastException;
}

Usage

$result = executeWithRetry(function() use ($db) {
    return $db->find()->from('users')->get();
});

Smart Retry with Error Detection

use tommyknocker\pdodb\exceptions\DatabaseException;

function smartRetry(callable $operation, int $maxRetries = 3): mixed
{
    $attempt = 0;
    $lastException = null;
    
    while ($attempt < $maxRetries) {
        try {
            return $operation();
        } catch (DatabaseException $e) {
            $lastException = $e;
            $attempt++;
            
            if (!$e->isRetryable()) {
                // Don't retry
                throw $e;
            }
            
            if ($attempt < $maxRetries) {
                $delay = 2 ** $attempt;
                sleep($delay);
            }
        }
    }
    
    throw $lastException;
}

Retry with Logging

function retryWithLogging(callable $operation, Logger $logger): mixed
{
    $maxRetries = 3;
    $attempt = 0;
    $lastException = null;
    
    while ($attempt < $maxRetries) {
        try {
            $logger->info("Attempt " . ($attempt + 1));
            return $operation();
        } catch (DatabaseException $e) {
            $lastException = $e;
            $attempt++;
            
            if ($e->isRetryable() && $attempt < $maxRetries) {
                $logger->warning("Retryable error, retrying...", [
                    'attempt' => $attempt,
                    'error' => $e->getMessage()
                ]);
                sleep(2 ** $attempt);
            } else {
                throw $e;
            }
        }
    }
    
    throw $lastException;
}

Next Steps