japmul / retries
一个带有可能等待重试功能的小型重试库。
v1.0.0
2018-03-22 14:15 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- phpunit/phpunit: ^6.5
This package is auto-updated.
Last update: 2024-09-05 01:01:17 UTC
README
重试
一个在抛出异常后帮助重试过程的库。
基本用法
<?php use Retries\Retry; use Retries\RetryFailureException; $procedure = function() { // This is the function that might produce an error. }; try { $retry = new Retry($procedure); $retry->setTryAmount(5); // Optional. Defaults to 3. $retry->run(); } catch (RetryFailureException $exception) { // All 5 times failed. }
尝试之间的等待
可以指定等待的时间长度。在每次失败尝试后,它将等待指定数量的秒数后再尝试。默认为 1
秒。
<?php $retry = new Retry(function() { // Your function. }); $retry->setWaitTime(5); $retry->run();
指定要抑制的异常
默认将被抑制的异常是 RuntimeException
。当您的程序抛出此异常时,它将静默继续并重试,直到达到尝试次数。其他异常将按常规抛出。可以更改预期的异常。
<?php $retry = new Retry(function() { throw new LogicException; }); $retry->setAcceptedException(LogicException::class); $retry->run();
检索原始异常
如果所有尝试都失败,并且您收到一个 RetryFailureException
,可以检索被抑制的异常。 RetryFailureException
有一个 getOriginalExceptions()
方法,该方法将返回所有被抑制的异常。
<?php use Retries\Retry; use Retries\RetryFailureException; $procedure = function() { // This is the function that might produce an error. }; try { $retry = new Retry($procedure); $retry->setTryAmount(5); // Optional. Defaults to 3. $retry->run(); } catch (RetryFailureException $exception) { $originalExceptions = $exception->getOriginalExceptions(); }