我有一个问题。
我需要处理 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(... );
}
但不知道为什么,我觉得这有点垃圾。还有其他解决方案吗?
最佳答案
将 if
语句放入 case
内。您无需重复错误号测试。
switch ($db->getLastErrno()) {
case 1452:
if (strpos($db->getLastError(), "constraint name created on db") !== false) {
throw new Exception(...);
}
break;
...
}
关于php - 处理具有相同错误号的 Mysql 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51365938/