CodeIgniter中的自定义异常

Kri*_*rma 2 codeigniter exception custom-exceptions

我想扩展在调用getMessage时返回自定义消息的异常类.

class MY_Exceptions extends CI_Exceptions{
     function __construct(){
        parent::__construct();
    }
    function getMessage(){
        $msg = parent::getMessage();
        return "ERROR - ".$msg;
    }
}
Run Code Online (Sandbox Code Playgroud)

MY_Exceptions放在核心文件夹中.抛出/处理异常如下:

try{
    throw new Exception('a message');
}catch (Exception $e) {
        echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)

目的是得到"错误 - 一条消息".但它总是返回"消息".当我尝试调试时,控件永远不会进入MY_Exception类.有什么我想念的吗?

Kys*_*lik 5

创建文件core/MY_Exceptions.php

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Exceptions extends Exception {

    public function __construct($message, $code = 0, Exception $previous = null) {
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; //edit this to your need
    }

}

class MyCustomExtension extends MY_Exceptions {} //define your exceptions
Run Code Online (Sandbox Code Playgroud)

  • 这有助于我在CI中创建自己的例外.谢谢! (2认同)