Best Practices for Processing Errors from Database in CodeIgniter

后端 未结 2 1195
小鲜肉
小鲜肉 2021-01-05 22:37

I have a table with a unique key (date + userid) in my web application database. When I try to insert record with existing date and

2条回答
  •  死守一世寂寞
    2021-01-05 23:09

    We use in our project constructions like these:

    $this->db->_error_number();  
    $this->db->_error_message();
    

    but this undocumented functions and in next releases this could change. Of course you can simply use standard php for mysql error handle function:

    mysql_errno()  
    mysql_error()
    

    internally CI use these functions.

    As for me the best practice is use in custom Model's base class (BaseModel)

    $this->db->_error_number();
    

    and determine error, next throw exception with information error message taken from

    $this->db->_error_message();
    

    All your Model derived from BaseModel, and call method to check last request for db error and your Model must handle exception, and process it (may be additionally log), of course you can implement check result as result value and avoid of throwing exception.

提交回复
热议问题