12 February 2009

PHP Errors and Exceptions

I learned something about php error handling the other day. I was digging through the docs and discovered how to catch errors, warnings, and such and then re-throw them as exceptions. This is great because I already implemented a default exception handling and logging system to catch all exceptions. Now I can use the same routines for PHP errors. The keys to making this work are the set_error_handler function and the ErrorException class. The set_error_handler has been around for a long time, but I have never really used it. This is a failing on my part. The ErrorException class seems to have been made especially for this type of operation. The ErrorException documentation shows exactly how to use these two things together for object oriented goodness in PHP.
<?php
  function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  }
  set_error_handler("exception_error_handler");
?>
The function name passed to set_error_handler will be called if there is ever a PHP error. The function set up to handle errors takes the error information, constructs an ErrorException and then throws it. Errors never go directly out to the user or logs, they are always wrapped in an exception. Doing this give you greater control over error handling.

In the user comments on the ErrorException page troelskn gives a suggestion for improvement to the basic example above. He suggests the following code.
<?php
function exception_error_handler($severity, $message, $filename, $lineno) {
  if (error_reporting() == 0) {
    return;
  }
  if (error_reporting() & $severity) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
  }
}
set_error_handler('exception_error_handler');
?>
This code allows the error reporting value set in php.ini to effect the behavior of the exception_error_handler. Only errors of a high enough severity will be passed on as exceptions. Using his code, if you have warnings suppressed, they will not raise an exception. They will just not be reported. I hope this removes one more of the little PHP quarks for you.

1 comment:

Anonymous said...

you have a very eclectic selections of posts