---
title: "Simple Way To Add Global Exception Handling In CodeIgniter"
url: https://thecancerus.com/simple-way-to-add-global-exception-handling-in-codeigniter/
date: 2010-10-02
modified: 2010-10-02
author: "ican"
description: "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..."
categories:
  - "how too?"
  - "php"
tags:
  - "codeigniter"
  - "exception handling"
word_count: 243
---

# Simple Way To Add Global Exception Handling In CodeIgniter

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](http://codeigniter.com/forums/viewthread/141573/) [forum](http://codeigniter.com/forums/viewthread/126752/) posts in CodeIgniter and [one](http://stackoverflow.com/questions/260597/in-codeigniter-how-can-i-have-php-error-messages-emailed-to-me) 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.