2017-01-18 256 views
0

我正在處理api,它處理來自客戶端的請求,然後從服務器獲取響應(使用codeigniter 3開發)並將其轉發回客戶。Codeigniter 3:無法使用try catch塊捕獲數據庫錯誤

但是,如果發生任何數據庫錯誤(如重複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。

任何幫助,將不勝感激。

+0

插入前請檢查數據庫中的值 –

+0

我試過檢查,但仍然沒有顯示錯誤。 – skm

+0

你如何驗證它?你可以在插入前用檢查代碼更新問題嗎? –

回答

1

至於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

如果你需要得到已發生的最後一個錯誤,該錯誤()方法返回一個包含其代碼數組消息

這在我看來有點不完整,因爲它不會在示例代碼中顯示錯誤代碼和錯誤消息。