我正在使用Laravel4.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秒。每次失败时,我都需要回滚更改,然后再试一次。
我怎么才能做好这件事?谢谢。
发布于 2015-10-07 10:50:49
我会将整个代码打包成一个执行事务/回滚的函数,并运行该函数,只要它返回false,并且它在不到10 s前就开始运行了。在我脑子里打字,也许我漏掉了什么东西,但我希望你能明白:
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) {
// :(
}https://stackoverflow.com/questions/32990014
复制相似问题