Skip to content

Instantly share code, notes, and snippets.

@pjcdawkins
Created March 2, 2016 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjcdawkins/fc42081596d25d723cbd to your computer and use it in GitHub Desktop.
Save pjcdawkins/fc42081596d25d723cbd to your computer and use it in GitHub Desktop.
Guzzle 5 - get a URL with retries
<?php
/**
* Get a URL, with automatic retries.
*
* @param \GuzzleHttp\Client $client
* @param string $url
* @param int|float $timeout
* @param int $max_attempts
*
* @throws \GuzzleHttp\Exception\RequestException
* If there is an HTTP failure.
* @throws \RuntimeException
* If there is an unexpected failure.
*
* @return \GuzzleHttp\Message\ResponseInterface
* The Guzzle HTTP response.
*/
function guzzle_get_retry(\GuzzleHttp\Client $client, $url, $timeout = 10, $max_attempts = 3) {
for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
try {
return $client->get($url, ['timeout' => $timeout]);
}
catch (\GuzzleHttp\Exception\RequestException $e) {
// Abort immediately on 5xx errors.
if ($e->hasResponse() && $e->getResponse()->getCode() >= 500) {
throw $e;
}
}
}
throw isset($e) ? $e : new \RuntimeException('Request failed to URL: ' . $url);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment