Skip to content

Instantly share code, notes, and snippets.

@flaviu-chelaru
Created October 1, 2019 06:44
Show Gist options
  • Save flaviu-chelaru/c7ece2998046e73fcc63f69ca059cc35 to your computer and use it in GitHub Desktop.
Save flaviu-chelaru/c7ece2998046e73fcc63f69ca059cc35 to your computer and use it in GitHub Desktop.
Retry exception handler
<?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);
}
}
<?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