O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Custom Error Handlers

While assert() is a good function to make extensive use of, it only catches errors you were expecting. While that might sound obvious, it is quite crucial—if an error you have not planned for occurs, how are you to find out about it? Never fear—there are two functions available to make your life much easier: set_error_handler() and error_log().

The set_error_handler() function takes the name of a user callback function as its only parameter, and it notifies PHP that any errors should use that function to handle them. The user function needs to accept a minimum of two parameters, but in practice you will likely want to accept four. These are, in order, the error number that occurred, the string version of the error, the file the error occurred in, and the line of the error. For example:

    function on_error($num, $str, $file, $line) {
            print "Encountered error $num in $file, line $line: $str\n";
    }

    set_error_handler("on_error");
    print $foo;

On line four, we define the general error handler to be the on_error() function, then call print $foo, which, as $foo does not exist, is an error and will result in on_error() being called. The definition of on_error() is as described: it takes four parameters, then prints them out to the screen in a nicely formatted manner.

There is a second parameter to set_error_handler() that lets you choose what errors should trigger the error handler, and it works like the error_reporting directive in php.ini. However, you can only have one ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required