PHP

Try / Retry With Logging

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Run a callable up to N times; log each failed attempt and bubble the last exception. Compact, no dependencies, useful for transient failures (S3 puts, email sends, etc.).
PHP
Raw
<?php
function retry(callable $fn, int $attempts = 3, int $delayMs = 200): mixed {
    for ($i = 1; $i <= $attempts; $i++) {
        try {
            return $fn();
        } catch (Throwable $e) {
            error_log("retry: attempt $i/$attempts failed — {$e->getMessage()}");
            if ($i === $attempts) throw $e;
            usleep($delayMs * 1000 * $i);   // linear back-off
        }
    }
    // unreachable
}

$resp = retry(fn() => httpGet('https://flaky.example.com/data'));
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.