我正在使用一个api,它处理来自客户端的请求,然后从服务器(使用codeigniter 3开发)中获取响应,并将其转发回客户端。
但是,如果发生任何数据库错误,例如重复的id或null值,则模型类将无法处理该错误以显示正确的错误消息。我已经尝试了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;
}
}
Run Code Online (Sandbox Code Playgroud)
值得一提的是,我已将db_debug设置为FALSE。
任何帮助,将不胜感激。
小智 7
对于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;
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅https://www.codeigniter.com/userguide3/database/queries.html#handling-errors中的文档
说
如果需要获取最近发生的错误,则error()方法将返回包含其代码和message 的数组。
我认为这有点不完整,因为它在示例代码中没有显示错误代码和错误消息。