[英]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.