Skip to content

Commit c7e51ce

Browse files
committed
Add options for retry on server error
1 parent 4117113 commit c7e51ce

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/Client.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,15 @@ class Client
7777
/** @var int Max number of retries if we get 429 errors */
7878
public $maxAttempts = 10;
7979

80+
/** @var int Max number of retries if we get 5XX errors */
81+
public $maxAttemptsOnServerError = 1;
82+
8083
/** @var float Number of seconds to sleep before retrying */
8184
public $sleepTimeOnRetry = 0.5;
8285

86+
/** @var float Number of seconds to sleep before retrying after a server error */
87+
public $sleepTimeOnServerError = 10;
88+
8389
/**
8490
* Create a new client to connect to a given Alma instance.
8591
*
@@ -241,12 +247,14 @@ public function request(RequestInterface $request, $attempt = 1)
241247
return $this->http->sendRequest($request);
242248
} catch (HttpException $e) {
243249
// Thrown for 400 and 500 level errors.
250+
$statusCode = $e->getResponse()->getStatusCode();
251+
244252
$error = $this->parseClientError($e);
245253

246254
if ($error->getErrorCode() === 'PER_SECOND_THRESHOLD') {
247255
// We've run into the "Max 25 API calls per institution per second" limit.
248256
// Wait a sec and retry, unless we've tried too many times already.
249-
if ($attempt > $this->maxAttempts) {
257+
if ($attempt >= $this->maxAttempts) {
250258
throw new MaxNumberOfAttemptsExhausted(
251259
'Rate limiting error - max number of retry attempts exhausted.',
252260
0,
@@ -258,6 +266,15 @@ public function request(RequestInterface $request, $attempt = 1)
258266
return $this->request($request, $attempt + 1);
259267
}
260268

269+
if ($statusCode >= 500 && $statusCode < 600) {
270+
if ($attempt >= $this->maxAttemptsOnServerError) {
271+
throw $error;
272+
}
273+
time_nanosleep(0, $this->sleepTimeOnServerError * 1000000000);
274+
275+
return $this->request($request, $attempt + 1);
276+
}
277+
261278
// Throw exception for other errors
262279
throw $error;
263280
} catch (NetworkException $e) {

0 commit comments

Comments
 (0)