在CodeIgniter中处理数据库错误的最佳实践 [英] Best Practices for Processing Errors from Database in CodeIgniter

查看:85
本文介绍了在CodeIgniter中处理数据库错误的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的web应用程序数据库中有一个具有唯一键( date + userid )的表。当我尝试插入记录与现有日期 userid 我收到以下错误:

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 userid I receive the following error:

dupicate key in table

我打开了应用程序配置中的数据库调试器,因为我需要使用MySQL错误号和消息。现在我需要处理这个错误。我可以在控制器中使用硬编码的常量,但我认为这不是好主意。我需要在许多地方的数据库错误处理,我不喜欢CodeIgniter的错误处理。

I turned on the database debugger in application config, because I needed to use MySQL error numbers and messages. Now I need to process this error. I can use hard coded constants in the controller, but I think it's not good idea. I need database error handling in many places, and I dont like CodeIgniter's error handling. What is a best practice concerning the processing of database errors.

推荐答案

我们在我们的项目结构中使用这些:

We use in our project constructions like these:

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

但是这个未记录的函数,在下一个版本中,这可能会改变。
当然你可以简单地使用标准php为mysql错误句柄函数:

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()

内部CI使用这些函数。

internally CI use these functions.

至于我最好的做法是在自定义模型的基类(BaseModel)中使用

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();

您的所有Model都派生自BaseModel,并且调用方法检查最后一个请求的db错误,处理异常,并处理它(可能另外日志),当然你可以实现检查结果作为结果值,避免抛出异常。

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.

这篇关于在CodeIgniter中处理数据库错误的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆