Monday, March 22, 2010

Replace built-in PHP fatal errors with exceptions

We may want to use Exception instead of php4 style error handling systems to make error handling more consistent. We can build a bridge from old error handling to the new Exception handling.

class PhpErrorException extends Exception {}

function errorHandler($errno, $errstr, $errfile, $errline) {
throw new PhpErrorException ($errstr,$errno);
}

$handler= set_error_handler('errorHandler');

Now you can test it. For example: run echo 5/0; and you will see an exception is thrown instead that a PHP warning is given off.

No comments: