[英]Codeigniter 3: Can't catch database error using try catch block
我正在开发一个 api,它处理来自客户端的请求,然后从服务器获取响应(使用 codeigniter 3 开发)并将其转发回客户端。
但是,如果出现任何数据库错误,例如重复 ID 或空值,模型类无法处理该错误以显示正确的错误消息。 我已经尝试过 try catch 块,但还没有成功。 这是模型:
public function add() {
try {
$this->db->trans_start(FALSE);
$this->db->insert('users', $preparedData);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
throw new Exception("Database error:");
return false;
}
return TRUE;
} catch (Exception $e) {
log_message('error: ',$e->getMessage());
return;
}
}
需要提及的一件事是,我已将 db_debug 设置为 FALSE。
任何帮助,将不胜感激。
至于 CI 3,下面的代码获取数据库错误代码和错误消息。 db_debug 设置为 FALSE。
public function add() {
try {
$this->db->trans_start(FALSE);
$this->db->insert('users', $preparedData);
$this->db->trans_complete();
// documentation at
// https://www.codeigniter.com/userguide3/database/queries.html#handling-errors
// says; "the error() method will return an array containing its code and message"
$db_error = $this->db->error();
if (!empty($db_error)) {
throw new Exception('Database error! Error Code [' . $db_error['code'] . '] Error: ' . $db_error['message']);
return false; // unreachable retrun statement !!!
}
return TRUE;
} catch (Exception $e) {
// this will not catch DB related errors. But it will include them, because this is more general.
log_message('error: ',$e->getMessage());
return;
}
}
请参阅https://www.codeigniter.com/userguide3/database/queries.html#handling-errors上的文档
说
如果您需要获取发生的最后一个错误,则 error() 方法将返回一个包含其code和message的数组。
我认为它有点不完整,因为它没有在示例代码中显示错误代码和错误消息。
上面代码中的建议
删除行$this->db->trans_complete();
如果我们在完成事务后看到$this->db->error()
它将始终为空
删除分号 - log_message('error :',$e->getMessage()); return;
log_message('error :',$e->getMessage()); return;
public function add()
{
try {
$this->db->trans_start(FALSE);
$this->db->insert('users', $preparedData);
// documentation at
// https://www.codeigniter.com/userguide3/database/queries.html#handling-errors
// says; "the error() method will return an array containing its code and message"
$db_error = $this->db->error();
if (!empty($db_error)) {
throw new Exception('Database error! Error Code [' . $db_error['code'] . '] Error: ' . $db_error['message']);
return false; // unreachable return statement !!!`enter code here`
}
return TRUE;
} catch (Exception $e) {
// this will not catch DB related `enter code here`errors. But it will include them, because this is more general.
log_message('error ',$e->getMessage());
return;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.