set_error_handler

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:

Our custom error handling function in actionsample

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.

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.