<?php
function withDbRetry(callable $reconnect, callable $work): mixed {
try {
return $work();
} catch (PDOException $e) {
$transient = str_contains($e->getMessage(), 'gone away')
|| str_contains($e->getMessage(), 'Lost connection')
|| str_contains($e->getMessage(), 'Broken pipe');
if (!$transient) throw $e;
$reconnect(); // caller hands us a fresh connection
return $work(); // single retry — let the next failure bubble
}
}
// usage in a long-running worker loop:
$rows = withDbRetry(
fn() => $GLOBALS['db'] = pdoConnect(...),
fn() => $GLOBALS['db']->query('SELECT id FROM jobs WHERE status = "pending"')->fetchAll()
);
Create a free account and build your private vault. Share publicly whenever you want.