here is a somehow simplified version of my preferred errorhandling-mechanism.
error_handler.php
PHP Code:
<?php
$GLOBALS['error_handler_stack'] = array();
$GLOBALS['error_handler_failat'] = 0; // fails at fatal errors, but continue at warnings
error_reporting(E_ALL);
set_error_handler('create_error');
function create_error($errno, $errstr, $errfile, $errline)
{
// determine errortype
switch ($errno) {
case 1 :
case 4 :
case 16 :
case 64 :
case 256 :
// level = error
$errlevel = 0;
break;
case 2 :
case 32 :
case 128 :
case 512 :
// level = warning
$errlevel = 1;
break;
case 8 :
case 1024 :
// level = notice
$errlevel = 2;
break;
}
// push error to stack
$GLOBALS['error_handler_stack'][] = array(
'errno' => $errno,
'errstr' => $errstr,
'errfile' => $errfile,
'errline' => $errline,
'errlevel' => $errlevel
);
// halt execution i fneed be
if ($errlevel <= $GLOBALS['error_handler_failat']) {
halt();
}
}
function is_error()
{
return count($GLOBALS['error_handler_stack']) > 0;
}
function halt()
{
// clear buffers
while (ob_get_level() > 0) ob_end_clean();
// print error stack
$errortypes = array( 0 => 'Error', 1 => 'Warning', 2 => 'Notice');
echo "<h1>an error has occurred</h1><em>error stack trace :</em><ul>";
foreach ($GLOBALS['error_handler_stack'] as $e) {
echo "<li><strong>(" . $errortypes[$e['errlevel']] . " #".$e['errno'] . ")</strong> ".htmlentities($e['errstr']);
echo "<br />In line " . $e['errline'] . " of file " . $e['errfile'] . "</li>";
}
echo "</ul>";
// stop execution
exit(-1);
}
?>
And some samplecode, that generates an error.
example.php
PHP Code:
<?php
require_once('error_handler.php');
function foo()
{
$result = divide(100, 0);
if (is_error())
return trigger_error("Oh my. Something went terrible wrong.", E_USER_WARNING);
return $result;
}
function divide($a, $b)
{
if ($b == 0)
return trigger_error("Division by zero..", E_USER_WARNING);
return $a / $b;
}
foo();
if (is_error())
halt();
?>
The above scripts produce the following output.
an error has occurred
error stack trace :
(Warning #512) Division by zero..
In line 84 of file C:\FoxServ\www\foo.php
(Warning #512) Oh my. Something went terrible wrong.
In line 77 of file C:\FoxServ\www\foo.php
This is often quite usefull information for debugging, since it is possible to determine not only where an error ocurred, but also witch piece of code is responsible for producing the error.
In the above example halting execution in divide() would inform you that the function had been called wrongly, but would keep you in the dark as to why this did happen. By using a stack to store a chain of errors, it becomes clear where the error origins.
Bookmarks