Sunday, March 31, 2013

Create your own Error Handler in PHP.

Hello friends,

Yesterday, one of my friend told me that he doesn't like the notice and warning shown in PHP. So I read over Internet and here's what I came up with.

So today in Developer's Blog I will tell you the way to create our own Error handler in PHP. By doing this, we can get rid of default errors shown in PHP.

You can create your own Error handler in PHP like this :

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if(!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting
            return;
    }

    switch($errno) {
            case E_USER_ERROR:
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
            exit(1);
            break;

            case E_USER_WARNING:
            echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
            break;

            case E_USER_NOTICE:
            echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
            break;

            default:
            echo "Unknown error type: [$errno] $errstr<br />\n";
            break;
        }

        /* Don't execute PHP internal error handler */
        return true;
    }

    // function to test the error handling
    function scale_by_log($vect, $scale)
    {
        if(!is_numeric($scale) || $scale <= 0) {
            trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
        }

        if(!is_array($vect)) {
            trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
            return null;
        }

        $temp = array();
        foreach($vect as $pos => $value) {
            if (!is_numeric($value)) {
                trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
                $value = 0;
            }
            $temp[$pos] = log($scale) * $value;
        }

        return $temp;
    }

    // set to the user defined error handler
    $old_error_handler = set_error_handler("myErrorHandler");

E.g.,

$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
$b = scale_by_log($a, M_PI);

Output :

My NOTICE [1024] Value at position 2 is not a number, using 0 (zero)

So this was the way you can create your own error handler in PHP.

Download Source Files

I hope this will help you and you will like it.

Don't forget to leave your comments.


Thank you

Ravinder


No comments:

Post a Comment