set_error_handler
I’m sure there’s been at least one time when you growled at PHP because of its error handling facilities, right? If so, then you’ll be glad to know that you can define your own error handling function for PHP to use instead of its default. This is possible thanks to the set_error_handler() function, whose signature looks like this:
string set_error_handler ( string error_handler)
The error_handler parameter should be the name of your custom defined error handling function. This function needs to accept 2 mandatory and 3 optional parameters, like this:
function my_error_handler ($errno, $errstr, $errfile, $errline, $errcontent)
{
// Custom error handling goes here
}
Once you’ve created your custom error handling function, you simply pass it to set_error_handler, like this:
<?php
function my_error_handler ($errno, $errstr, $errfile, $errline, $errcontent)
{
echo “<font color=’red’><b>An Error Occured!</b></font><br>”;
echo “<b>Error Number:</b> $errno<br>”;
echo “<b>Error Description:</b> $errstr<br>”;
echo “<b>Error In File:</b> $errfile<br>”;
echo “<b>Error On Line:</b> $errline<br>”;
}
set_error_handler(”my_error_handler”);
$x = 5/0;
?>
As you can see on the second last line, I’ve raised a divide by zero error. Here’s how to error appeared in my browser:


Set_error_handler() is ideal for situations where a task must be performed when an error occurs, such as deleting temporary files, freeing memory, closing database connections, etc. It’s also a handy way to track and log errors on a development server when performing desktop checks, etc.
