Laravel:使用try ... catch与DB :: transaction() [英] Laravel: Using try...catch with DB::transaction()
问题描述
我们都使用DB::transaction()
进行多个插入查询.这样做时,应该将try...catch
放在其中还是将其包装?如果事务出了错,事务会自动失败,是否甚至需要包含try...catch
?
We all use DB::transaction()
for multiple insert queries. In doing so, should a try...catch
be placed inside it or wrapping it? Is it even necessary to include a try...catch
when a transaction will automatically fail if something goes wrong?
示例try...catch
包装交易:
// try...catch
try {
// Transaction
$exception = DB::transaction(function() {
// Do your SQL here
});
if(is_null($exception)) {
return true;
} else {
throw new Exception;
}
}
catch(Exception $e) {
return false;
}
相反,DB::transaction()
包装了try ... catch:
The opposite, a DB::transaction()
wrapping a try...catch:
// Transaction
$exception = DB::transaction(function() {
// try...catch
try {
// Do your SQL here
}
catch(Exception $e) {
return $e;
}
});
return is_null($exception) ? true : false;
或者只是没有try ... catch的交易
Or simply a transaction w/o a try...catch
// Transaction only
$exception = DB::transaction(function() {
// Do your SQL here
});
return is_null($exception) ? true : false;
推荐答案
如果您需要通过代码手动退出"交易(通过异常还是只是检查错误状态),则不应使用DB::transaction()
,而是将您的代码包装在DB::beginTransaction
和DB::commit
/DB::rollback()
中:
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction()
but instead wrap your code in DB::beginTransaction
and DB::commit
/DB::rollback()
:
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
请参见交易文档.
这篇关于Laravel:使用try ... catch与DB :: transaction()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!