Currently I am working on a REST API application using the CodeIgniter 3x framework. I quickly realized that methods in the core Exception class did not completely suite my needs. I decided to extend the exception class, which is the recommended way, instead of modifying the Exception class itself.

The following are steps that I took to achieve it.

Create the Exception Sub-class

In your application/core folder create a new file and name it MY_Exceptions.php. I am assuming that the value of your config['subclass_prefix'] in your config.php file is “MY_”. If it is not please replace the “MY_”  in “MY_Exceptions.php” with the correct value.

MY_Exceptions.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');
 
 class MY_Exceptions extends CI_Exceptions {
 	
  function __construct()
  {
      parent::__construct();		
  }
  
  public function show_custom_error($message)
  {
      //add your logic
      //assign your $header, $template, and $status values	
      //if needed you can also call the show_error method of the parent class.
      return $this->show_error($header, $message, $template, $status);	
  }
}

Create Exception helper function

Now you have a sub-class of the core Exception class. Next step is to make your custom method to be globally available so that you can directly call show_custom_error('some error occurred'); from anywhere be it from a controller or model class. To achieve this you would have to create an exception helper function. In your application/helpers folder create a new file called exceptions_helper.php and paste in the following code.

exceptions_helper.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Defines common exception functions that are globally available
 */
 
if ( ! function_exists('show_custom_error'))
{
    function show_custom_error($message)
    {
        $_error =& load_class('Exceptions', 'core');
        echo $_error->show_custom_error($message);
        exit;
    }
}

Autoad the Exception helper

Finally enable the exception helper to be loaded automatically by adding it to the helper autoload array in the application/config/autoload.php file.

autoload.php

.
.
.
$autoload['helper'] = array('exceptions');
.
.
.

And you are all set, you can now call you custom exception method from anywhere. show_custom_error('some error occurred');