2

I want to extend the exception class that returns custom message when getMessage is called.

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

MY_Exceptions is placed in core folder. And the exception throwing / handling is as follows:

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

The intention is to get "ERROR - a message". But it always returns "a message". When I try debugging, the control never goes to MY_Exception class. Is there anything that I am missing?

Krishna Sarma
  • 1,852
  • 2
  • 29
  • 52
  • First off your exception is not "custom" its normal exception with a message, custom exception is something like `MyCustomException('message');`, I looked at exceptions.php (in CI's system/core) and it seems that CI_Exceptions does not extend php exception. Please do further reading [here](http://php.net/manual/en/language.exceptions.extending.php). – Kyslik Dec 12 '14 at 18:31

1 Answers1

7

Create file 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
Kyslik
  • 8,217
  • 5
  • 54
  • 87