[thelist] free tip: PHP4 error handling

sbeam sbeam at syxyz.net
Fri Nov 12 12:14:11 CST 2004


<tip author="S Beam" type="Error handling in PHP4">
PHP's built-in functions set_error_handler() and trigger_error() can be 
used to automatically send an email containing a full debugging dump 
concerning any error to the developers, while providing a nice, 
innocuous, non-heart-attack-inducing message to the user.

In your init.php script (or equivalent that is prepended to every 
invocation of php) have the line
set_error_handler ('my_error_handler');

then write a function like this:

function my_error_handler ($errno, $errstr, $errfile, $errline) {
    mail(ERROR_RECIPIENT, "ERROR on the site", "Error $errno at $errline 
of $errfile: [$errstr]");
    // other stuff... 
    print "What did you do? You broke it."; // this goes to the screen
}

Then in your application, when you come across a condition where you 
would have used die() or exit(), just do this, e.g.:

trigger_error("Couldn't connect to the DB!", E_USER_ERROR);

Season to taste. The mail will go out and you will not need to hope the 
user will call you and read the error message to you or anything like 
that. You could also include a dump of all POST, GET, SESSION or any 
other variables in your mail to see exactly what the state was when the 
error occurred.

</tip>


-- 

# S Beam - Web App Dev Servs
# http://www.onsetcorps.net/


More information about the thelist mailing list