0

我正在尝试在我的模型和控制器中使用异常。在application, 目录中,我创建了一个目录Exceptions,其中包含文件“CustomException1.php”和“CustomException2.php”中的一些异常类。

我定义MY_Controllerapplication/core

class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();      

        // include Exception files
        require_once(APPPATH . 'Exceptions/CustomException1.php');
        require_once(APPPATH . 'Exceptions/CustomException2.php');
    }

}

在我的控制器中Test

class Test extends MY_Controller {
   public function index() {
      try {
         throw new CustomException1('This is a custom exception');
      } catch (CustomException1 $e) {
         $this->output->set_status_header('500');
         echo $e->message;
      }
}

现在,我希望这可以工作,因为我需要定义异常类的所有文件,但我仍然收到一条错误消息

Class CustomException1 not found on line xx

4

2 回答 2

0

无论出于何种原因,包括 Exceptions 目录中的文件都无法在 CI 中工作。将它们放在libraries目录中并将它们加载到 using 中$this->load->library()也不会起作用,因为 CI 会在加载时尝试实例化库,这当然是我不想要的。

我最终把它们放在一个目录exceptionshelpers,并在MY_Controller使用时加载它们$this->load->helper('Exceptions/CustomException');

需要注意的是,在加载帮助程序时,CI 会将整个路径转换为小写并附_helper加到文件名的末尾,因此我的异常类在服务器上的确切路径是

APPPATH . 'helpers/exceptions/customexception_helper.php'

这是我修改后的基类控制器:

class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();      

        $this->load->helper("Exceptions/CustomException1.php");
        // includes file APPPATH . 'helpers/exceptions/customexception1_helper.php'

        $this->load->helper("Exceptions/CustomException2.php");
        // includes file APPPATH . 'helpers/exceptions/customexception2_helper.php'
    }
}

一旦MY_Controller使用MY_Model.

PS - 我对这个解决方案并不完全满意,而且看起来有点 hack-y,但这可能是将异常集成到 CodeIgniter 的唯一方法。

于 2013-02-05T07:19:22.307 回答
0
throw new CustomException1('This is a custom exception');

并捕获 (CustomException $e)

tbh,这更像是一个错字。抛出的异常CustomException1应该是CustomException

于 2013-02-04T20:12:50.187 回答