我正在使用Laravel 4.2我有一个巨大的try/catch
块用于运行数据库事务。有多种类型的例外。
$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
}
我希望整个过程重试10秒钟。在每次失败时,我都需要回滚更改并重试。
我该如何正确地做到这一点? 感谢。
答案 0 :(得分:1)
我将整个代码包装在&#34;尝试&#34;进入执行事务/回滚的函数,并运行该函数,只要它返回false并且它开始运行不到10年前。从我脑海里打字,也许我错过了一些东西,但我希望你能得到这样的结果:
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));
更新,根据评论:
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;
}
所以,基本上你可以这样称呼:
$success = tryFor10Seconds(function() use ($model1, $model2, $whatever) {
$model1->save();
$model2->save();
$whatever->doSomethingWithDB();
});
if (!$success) {
// :(
}