Catching most PHP errors

By | May 6, 2007

When developing in PHP you may have encountered the following problem:

During an upgrade of the code, or just a minor bug fix, you have introduced new (non critical-error) code. This is causing PHP to crash and report ugly warnings to the user.

Well I think most developers of PHP have found this problem. One option, which is always done on live servers, is setting the logging level very low. Only critical errors are displayed. Though effective it’s far from perfect. I know I want to know when a page is creating problems, even if it is just a minor bug.

PHP has a nifty little feature that allows you to set a error handler, overwriting the default. By doing so you can catch all those nasty little errors before they go to the user. But what’s even better is that you can do anything with the information. The function to do this is called:

set_error_handler( “functionname” );
Sets the default PHP error handler to a custom function rather then the PHP default error handling.

Why is this useful, well let me give you a prototype of a function that catches the errors:

function handleErrors($errno, $errstr, $errfile, $errline){
 switch ($errno){
    Handler::Log('<b>User Error:</b> '. $errstr, $errline);
    Handler::Error('<b>Unknown Error:</b> '. $errstr, $errline);

So what does it do. Well it’s pretty straight forward. When an error occurs this function gets called. The errno is described at the PHP manual for set_error_handler. What I’ve done is calling a function on one of my classes. This specific class will construct an e-mail per page view and sent it if there are any errors.

But you’re free to do what ever you want with the errors PHP throws at you, from logging to a file to crashing output (if that’s what turns you on :)). Experiment a little!

PS: keep track of the fact that compiling errors will still cause the pages to crash

Leave a Reply