Reputation: 1190
I am using Laravel 4.2 I have a huge try/catch
block for running database transactions. With multiple types of exceptions.
$startTime = 0;
try {
DB::beginTransaction();
//code
DB::commit();
}catch(Exception1 $e){
DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process
}catch(Exception2 $e){
DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process
}catch(Exception $e){
DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process
}
I want the whole process to retry for 10 seconds. On every fail I need to rollback the changes and try again.
How can I do this properly? Thanks.
Upvotes: 1
Views: 2071
Reputation: 3262
I'd wrap the entire code in "try" into a function that performs the transaction/rollback, and run the function as long as it returns false and it started running less than 10s ago. Typing out of my head, maybe I missed something but I hope you get the picture:
function doIt() {
try {
DB::beginTransaction();
/**
* whatever
*/
DB::commit();
return true;
} catch (Exception $e) {
DB::rollBack();
/**
* do something more if you need
*/
return false;
}
}
$start = time();
do {
$IdidIt = doIt();
} while(!$IdidIt && (time() - $start <= 10));
UPDATE, according to the comment:
function tryFor10Seconds(Closure $closure) {
$runTheClosure = function ($closure) {
try {
DB::beginTransaction();
$closure();
DB::commit();
return true;
} catch (Exception $e) {
DB::rollBack();
// handle the exception if needed, log it or whatever
return false;
}
};
$start = time();
do {
$result = $runTheClosure($closure);
} while(!$result && (time() - $start <= 10));
return $result;
}
So, basically you'd call this like:
$success = tryFor10Seconds(function() use ($model1, $model2, $whatever) {
$model1->save();
$model2->save();
$whatever->doSomethingWithDB();
});
if (!$success) {
// :(
}
Upvotes: 1