Created
March 2, 2016 11:56
-
-
Save pjcdawkins/fc42081596d25d723cbd to your computer and use it in GitHub Desktop.
Guzzle 5 - get a URL with retries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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