1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class DataSync { function sync() { // [...] $details = $this->retryOnApiFailure( function () use ($userId) { return $this->repository->findOneById($userId); } ); // [...] } /** * Retry API calls when we get a "502 Bad Gateway" response 3 times */ protected function retryOnApiFailure($functionToCall, int $try = 1): mixed { $v = OutputInterface::VERBOSITY_VERBOSE; if ($try === 2) { $this->io->writeln(' retrying API call', $v); } elseif ($try === 3) { $this->io->writeln(' retrying API call a second time in 10s', $v); sleep(10); } elseif ($try === 4) { $this->io->writeln(' retrying API call a third time in 30s', $v); sleep(30); } try { return $functionToCall(); } catch (\GuzzleHttp\Exception\ServerException $e) { if ($e->getCode() === 502) { if ($try >= 4) { throw $e; } return $this->retryOnApiFailure($functionToCall, $try + 1); } } } |