feat: add retry client trait for api requests
feat: add retry client trait for api requests
This commit is contained in:
58
src/Service/Remote/RetryingFailClientTrait.php
Normal file
58
src/Service/Remote/RetryingFailClientTrait.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Remote;
|
||||
|
||||
use Exception;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
trait RetryingFailClientTrait
|
||||
{
|
||||
/**
|
||||
* Lepsi zopakovat request kvuli drobnemu vypadku site nebo sluzby (u nedestruktivni operace)
|
||||
* nez hodit klientovi rovnou 500
|
||||
*
|
||||
* @param int $count
|
||||
* @param float $sleep
|
||||
* @param array<string> $catchableExceptions
|
||||
* @param LoggerInterface $logger
|
||||
* @param callable $callback
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function retryingFailRequest(
|
||||
int $count,
|
||||
float $sleep,
|
||||
array $catchableExceptions,
|
||||
LoggerInterface $logger,
|
||||
callable $callback
|
||||
): mixed {
|
||||
for ($i = 0; ; $i++) {
|
||||
try {
|
||||
return $callback();
|
||||
} catch (Exception $e) {
|
||||
foreach ($catchableExceptions as $exceptionClass) {
|
||||
if ($e instanceof $exceptionClass) {
|
||||
$logger->error("transport: fail request retrying... got catchable exception", [
|
||||
'exception' => $e,
|
||||
'try' => $i
|
||||
]);
|
||||
|
||||
usleep((int) ($sleep * 1_000_000));
|
||||
|
||||
if ($i == $count) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
// phpstan fail
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user