I am working on a project where we needed to capture exceptions at a global level instead of doing it at every step as they were not critical, but important for us to know.
The idea was that whenever such an exception occur on production we should send an email to developers mailing list so that someone can investigate it.
As usual I did a quick google search and i found two forum posts in CodeIgniter and one on stackoverflow, but they all fall short as CodeIgniter does not set’s any default exception handlers they way it sets the native error handler.
So here is a quick tutorial on how you can do that.
First of all you need to setup a hook, so put following code in hook.php file in config folder.
$hook['pre_controller'] = array( 'class' => 'ExceptionHook', 'function' => 'SetExceptionHandler', 'filename' => 'ExceptionHook.php', 'filepath' => 'hooks' );
Now I am using pre_controller hook as I wanted to use $CI object which is available at this stage.
Now put the code shown below in the file named ExceptionHook.php in your application’s hooks folder.
Also if you need to capture and email native PHP errors, you can do so by extending the Exceptions library as shown in the code below.
While I have used the simple PHP mail function in the example above, you can use CI’s mail library as well.
If you have any doubts feel free to ask in comments below.