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?

1
  • 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. Commented Dec 12, 2014 at 18:31

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

This helped me to create my own Exceptions in CI. Thank you!
@luis.ap.uyen - I know its too late, but can you share the implementation
@VimalMahi are you on legacy project? If not and you are just starting; see other frameworks (like Laravel) instead; way better learning curve with laracasts.com etc.
Thanks for the revert @Kyslik! Will definitely look into Laravel

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.