Akash KC
Akash KC

Reputation: 16310

Exception Handling in CodeIgniter

Recently, I'm learning the PHP with CodeIgniter Framework. I am working on exception handling but one thing astonished me that exception handling does not work with database error when there is db_debug = TRUE in database.php setting.

If db_debug = FALSE, I can throw and catch the error but when it's TRUE, it directly displays the page with database error.

Here is my code :

In Model :

    $this->db->insert('tbl_name',$data);
    if (strpos($this->db->_error_message(),'constraint_name') !== FALSE)
    {
        throw new UniqueConstraintException($this->db->_error_message()); // UniqueConstraintException is customized excpetion
    }

In Controller :

        try
        {
             //calling the method from model having above code
        }
        catch(UniqueConstraintException $ex)
        {
              echo "There is already item with same item name";
        }
        catch(Exception $ex)
        {
             echo $ex->getMessage();
        }

Can I implement exception handling on database error even if there is db_debug = TRUE setting?

Upvotes: 4

Views: 8061

Answers (1)

Francois Bourgeois
Francois Bourgeois

Reputation: 3690

The CodeIgniter guys don't know anything about oop. When you look into the code, you'll find things like this a million times in the DB driver (don't know anything about DRY, either):

if (<some condition>) {
    if ($this->db_debug) {
        log_message('error', 'Invalid query: '.$sql);
        return $this->display_error('db_invalid_query');
    }
    return FALSE;
}

So no, you cannot disable this "feature". You could however extend the class CI_DB_driver to get rid of this problem, but due to the lack of DRY code you'll have to override nearly everything of this class...

Upvotes: 12

Related Questions