PHP Error Handling, Exceptions and Development

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

Often when creating new code, you want the system to die on any kind of error so that you can be sure that there are no bugs lurking in minor errors that are actually having a major effect.

An easy way to do this is to do this:

create a file called error_handler.php with the following contents:

/* File error_handler
 * Edmonds Commerce
 * 0844 357 0201

function ec_error_handler($severity, $message, $filename, $lineno) {
  /*if (error_reporting() == 0) {
  if (error_reporting() & $severity) {*/
    throw new ErrorException($message, 0, $severity, $filename, $lineno);

function ec_exceptions_handler(Exception $e){
    h(1, 'Uncaught Exception');
    h(2, $e->getMessage());
    h(3, 'Line ' . $e->getLine() . ' of ' . $e->getFile());
    foreach($e->getTrace() as $t){


(Note the h function is this:)

function h($n, $t){
echo "<h$n>$t</h$n>";

Now include that file somewhere and all of your tiniest errors will throw an exception and dump a stack trace for you.

This is great for bug hunting.

You will notice that there is some commented out code in the ec_error_handler. Uncomment this if you want the error reporting level to be that of your php.ini settings.

As it is it will throw exceptions for everything, but for bug hunting that’s good I think