php 中事务的用法(以及日志记录)

try catch只会捕捉程序异常!
Db::startTrans();
try{
self::changeUserMoney($data);
Db::commit();
exit(‘success’); //返回成功 不要删除哦
}catch (\Exception KaTeX parse error: Expected '}', got 'EOF' at end of input: …ts('error.txt',data.PHP_EOL,FILE_APPEND);
Db::rollback();
exit(‘fail’);
}
echo 1;
不管事务中是否出错,echo 1始终会执行;

public function index(){
Db::startTrans();
try{
Db::name(‘user’)->setDec(‘a’,1);
}catch (\Exception KaTeX parse error: Expected '}', got 'EOF' at end of input: … new Exception(exception->getMessage());
Log::error($exception->getMessage());
}
dump(‘这里始终会执行!’);
}
这种情况不会执行会抛出异常!后续不会执行!

public function index(){
Db::startTrans();
try{
Db::name(‘user’)->setDec(‘a’,1);
}catch (\Exception $exception){
$err = [
‘code’ => $exception->getCode(),
‘msg’ => $exception->getMessage(),
‘file’ => $exception->getFile(),
‘line’ => e x c e p t i o n − > g e t L i n e ( ) ] ; @ f i l e p u t c o n t e n t s ( ′ e r r o r . t x t ′ , j s o n e n c o d e ( exception->getLine() ]; @file_put_contents('error.txt', json_encode( exception>getLine()];@fileputcontents(error.txt,jsonencode(err).PHP_EOL ,FILE_APPEND);
}
}

下面这种情况,如果需要手动抛出的异常可在有异常的地方处理,然后会进入到catch中然后再进行抛出。
public function index(){
Db::startTrans();
try{
self::changeUserMoney();
Db::commit();
exit(‘success’);
}catch (\Exception KaTeX parse error: Expected '}', got 'EOF' at end of input: … new Exception(exception->getMessage());
$err = [
‘code’ => $exception->getCode(),
‘msg’ => $exception->getMessage(),
‘file’ => $exception->getFile(),
‘line’ => e x c e p t i o n − > g e t L i n e ( ) ] ; @ f i l e p u t c o n t e n t s ( ′ e r r o r . t x t ′ , j s o n e n c o d e ( exception->getLine() ]; @file_put_contents('error.txt', json_encode( exception>getLine()];@fileputcontents(error.txt,jsonencode(err).PHP_EOL ,FILE_APPEND);
}
}
public function changeUserMoney(){
r e s = D b : : n a m e ( ′ s a l e s m a n ′ ) − > w h e r e ( " i d " , 4 ) − > u p d a t e ( [ ′ s t a t u s ′ = > 0 ] ) ; i f ( e m p t y ( res=Db::name('salesman')->where("id",4)->update(['status'=>0]); if(empty( res=Db::name(salesman)>where("id",4)>update([status=>0]);if(empty(res)){
throw new Exception(‘更新失败!’);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值