A way to handle errors in PHP

January 4th, 2008

Found a built-in error handling in PHP that can be useful in future versions of ClanWeb.

<?php// define a custom error handler

set_error_handler('oops');

// initialize the $string variable

$string = 'a string';

// explode() a string
// this will generate a warning because the number of arguments to explode() is incorrect
// the error will be caught by the custom error handler

explode($string);

// custom error handler

function oops($type, $msg, $file, $line, $context) {
   echo "<h1>Error!</h1>";
    echo "An error occurred while executing this script. Please contact the <a href=mailto:webmaster@somedomain.com>webmaster</a> to report this error.";
    echo "<p />";
    echo "Here is the information provided by the script:";
    echo "<hr><pre>";
    echo "Error code: $type<br />";
    echo "Error message: $msg<br />";
    echo "Script name and line number of error: $file:$line<br />";
    $variable_state = array_pop($context);
    echo "Variable state when error occurred: ";
    print_r($variable_state);
    echo "</pre><hr>";
}
?>

Example nr 2:

<?php// define a custom error handler
set_error_handler('oops');

// initialize $string variable$string = 'a string';

// this will generate a warningexplode($string);

// custom error handlerfunction oops($type, $msg, $file, $line, $context) {
    switch ($type) {
        // notices
        case E_NOTICE:
            // do nothing
            break;

// warnings        case E_WARNING:
            // report error
            print "Non-fatal error on line $line of $file: $msg <br />";
            break;

// other        default:
            print "Error of type $type on line $line of $file: $msg <br />";
            break;
    }

}
?>

Hopefully this functions could smoothen the error reporting in the future.