Exceptions > Errors

Today, whilst working with some PHP code, I wanted to catch an error like an exception.

PHP’s errors are a kludgey solution left-over from before PHP had objects. When PHP 5 introduced proper Exception support, I was overjoyed - until I learned that all the existing inbuilt PHP functions would continue to trigger errors rather than throwing exceptions. I understand that it’s necessary for backwards-compatibility, but it still really, really sucks when you want to write clean code.

So, today I was writing my own code to convert errors into exceptions when I hit a frustrating roadblock: the PHP Exception class doesn’t allow you to alter the stack trace. This is a Bad Thing in this case because you must throw the exception inside your error handler - which means that the stack trace starts at your error handling function, making the entire stack trace bloody useless.

Whilst Googling around I happened upon a few snippets here and there about the existence of an ErrorException in the SPL extension of PHP 5.1+. It is a wonderful thing - it’s basically an exception, with the added ability to pass in the stuff passed to a custom error handler, which is then put in the stack trace. It is truly a godsend for debugging.

Anyway, because I have a memory like a sieve and mentions of ErrorException are scarce, here’s the minimal code to use it:

function errorToExeption($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr,0,$errno,$errfile,$errline);
}
set_error_handler('errorToException');

That’s it - now you can treat any function that triggers errors like it throws exceptions instead. You might like to create a couple of subclasses of ErrorException for errors, warnings, etc. and then throw the appropriate exception inside your error handler. Don’t forget that a custom error handler can’t catch every type of error, such as those that might leave PHP in an unstable state, or those that occur inside the Zend Engine before your script is executed.

Posted on Friday, July 7th, 2006 at 6:01 pm | Tags: All Posts, Geeky Stuff, PHP, Web Development | Comments RSS Feed | No comments on this post | No trackbacks on this post

Comments are closed.