【问题标题】:Exception Handling in CodeIgniterCodeIgniter 中的异常处理
【发布时间】:2013-01-12 19:19:49
【问题描述】:

最近,我正在学习 PHPCodeIgniter 框架。我正在处理异常处理,但有一件事让我感到惊讶,当database.php 设置中有db_debug = TRUE 时,异常处理不适用于数据库错误。

如果是db_debug = FALSE,我可以抛出并捕获错误,但是当它是TRUE时,它会直接显示有数据库错误的页面。

这是我的代码:

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
    }

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

即使有db_debug = TRUE设置,是否可以对数据库错误进行异常处理?

【问题讨论】:

    标签: php codeigniter exception-handling codeigniter-2


    【解决方案1】:

    CodeIgniter 的人对 oop 一无所知。当您查看代码时,您会在 DB 驱动程序中发现一百万次这样的事情(对 DRY 也一无所知):

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

    所以不,您不能禁用此“功能”。但是你可以extend the classCI_DB_driver 来解决这个问题,但是由于缺少 DRY 代码,你必须重写这个类的几乎所有东西......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-09
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多