我有个问题。
我需要处理Mysql错误(例如重复键,外部约束...),例如:
$id=$db->insert ('user', $data);
if(!$id){
switch($db->getLastErrno()){
throw new Exception(... );
}
}
在这里,我使用错误号来选择正确的例外。
但是对于同样的错误,我该怎么办?
我认为使用错误字符串,例如:
if($db->getLastErrno()==1452 && strpos($db->getLastError(), "contraint name created on db")>-1){
throw new Exception(... );
}
但是我不知道为什么,我认为这有点浪费。有人有其他解决方案吗?
答案 0 :(得分:0)
将if
语句放在case
内。您无需重复错误编号测试。
switch ($db->getLastErrno()) {
case 1452:
if (strpos($db->getLastError(), "constraint name created on db") !== false) {
throw new Exception(...);
}
break;
...
}