Our blog

 

PHP Error Handling, Exceptions and Development

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:

PHP:
  1. <?php
  2. /* File error_handler
  3. * Edmonds Commerce
  4. * www.edmondscommerce.co.uk
  5. * info@edmondscommerce.co.uk
  6. * 0844 357 0201
  7. */
  8.  
  9. function ec_error_handler($severity, $message, $filename, $lineno) {
  10.   /*if (error_reporting() == 0) {
  11.     return;
  12.   }
  13.   if (error_reporting() & $severity) {*/
  14.     throw new ErrorException($message, 0, $severity, $filename, $lineno);
  15.   /*}*/
  16. }
  17. set_error_handler('ec_error_handler');
  18.  
  19. function ec_exceptions_handler(Exception $e){
  20.     h(1, 'Uncaught Exception');
  21.     h(2, $e->getMessage());
  22.     h(3, 'Line ' . $e->getLine() . ' of ' . $e->getFile());
  23.     foreach($e->getTrace() as $t){
  24.         var_dump($t);
  25.     }
  26.     die;
  27. }
  28.  
  29. set_exception_handler('ec_exceptions_handler');

(Note the h function is this:)

PHP:
  1. function h($n, $t){
  2. echo "<h$n>$t</h$n>";
  3. }

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

More Reading:

 

Leave a Reply