CodeIgniter中的自定义异常

时间:2014-12-12 17:41:45

标签: codeigniter exception custom-exceptions

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

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

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

try{
    throw new Exception('a message');
}catch (Exception $e) {
        echo $e->getMessage();
}

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

1 个答案:

答案 0 :(得分:5)

创建文件核心/ 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