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(‘更新失败!’);
}
}