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

skm picture skm · Jan 18, 2017 · Viewed 19.1k times · Source

I'm working on an api, it handles the requests which comes from clients, then gets the response from server(developed using codeigniter 3) and forwards that back to client.

But, in case of any database errors, like duplicate id, or null values, the model class cannot handle that error to display a proper error message. I've tried the try catch block but not succeeded yet. Here's the model:

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;
    }
}

One thing to mention, I've set db_debug to FALSE.

Any help would be appreciated.

Answer

Ahmet Çavdar picture Ahmet Çavdar · Sep 18, 2017

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.