Created
October 1, 2019 06:44
-
-
Save flaviu-chelaru/c7ece2998046e73fcc63f69ca059cc35 to your computer and use it in GitHub Desktop.
Retry exception handler
This file contains hidden or 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 | |
class ExceptionHandler { | |
public static function retry(\Closure $main, ?\Closure $onFailure = null, $tries = 10) { | |
$throwable = null; | |
try { | |
call_user_func($main); | |
} catch(\Throwable $throwable) { | |
// i would advise catching only specfic exceptions here | |
// i created a RetryException extends \Exception for this purpose | |
// so i only retry instances of RetryException that are throw custom by me - allows me better control over what exceptions i retry | |
$tries--; | |
} | |
if($tries == 0) { | |
throw $throwable; | |
} | |
if($onFailure instancef \Closure) { | |
$onFailure($tries); | |
} | |
return self::retry($main, $onFailure, $tries); | |
} | |
} |
This file contains hidden or 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 | |
include_once 'ExceptionHandler.php'; | |
ExceptionHandler::retry(function(){ | |
// perform inconsistent operation here | |
// examples: http request to a server that might throw 500 errors randomly | |
// example2: retry db operation that sometimes might fail | |
// example3: retry operations on locked resources | |
}, null, 5); | |
ExceptionHandler::retry(function(){ | |
// operations here | |
$data = $cache->get('key'); | |
if($data) | |
{ | |
return $data; | |
} | |
$response = $http->get('http://example.com'); | |
$cache->set('key', $response); | |
return $response; | |
}, function(int $tries){ | |
sleep(5); | |
$cache->forget('key'); // on failure clear the cache | |
}, 5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment