我正在开发一个 api,它处理来自客户端的请求,然后从服务器获取响应(使用 codeigniter 3 开发)并将其转发回客户端。
但是,如果出现任何数据库错误,例如重复 ID 或空值,模型类将无法处理该错误以显示正确的错误消息。我试过 try catch block 但还没有成功。 这是模型:
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 处的文档
说
If you need to get the last error that has occurred, the error() method will return an array containing its code and message.
我认为它有点不完整,因为它在示例代码中没有显示错误代码和错误消息。
关于php - 代码点火器 3 : Can't catch database error using try catch block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716175/