Codeigniter - How to Catch Db Errors

CodeIgniter - how to catch DB errors?

Use error() method:

$this->db->error(); 

For CodeIgniter 2, you can use the following functions which are now deprecated:

$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)

Codeigniter 3: Can't catch database error using try catch block

As for CI 3, below code gets database error code and error message. db_debug is set to 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;
}
}

Refer to documentation at https://www.codeigniter.com/userguide3/database/queries.html#handling-errors

saying

If you need to get the last error that has occurred, the error() method will return an array containing its code and message.

It is a bit incomplete in my opinion because it does not show error code and error message in the example code.

Check codeigniter query errors instead of showing them to the user

In application/config/database.php set

// suppress error output to the screen
$db['default']['db_debug'] = FALSE;

In your model or controller:

// try the select.
$dbRet = $this->db->select($table, $dataArray);
// select has had some problem.
if( !$dbRet )
{
$errNo = $this->db->_error_number();
$errMess = $this->db->_error_message();
// Do something with the error message or just show_404();
}

Database Error Handling problem in CodeIgniter

You need to throw an exception if there was some mysql error:

try {
$query_str = "SELECT * FROM tbl_user WHERE username = '".$username."'";
$result = $this->db->query($query_str);

if (!$result)
{
throw new Exception('error in query');
return false;
}

return $result;

} catch (Exception $e) {
return;
}


Related Topics



Leave a reply



Submit