PHP Custom Error Handler
Oct 5th, 2008
This is custom error handler in PHP. You can use your custom error handler for showing the error in you customized format, logging the error in a log file and for other reason.
<?php
//error handler function
function customError($errno, $errstr, $fileName, $lineNo)
{
switch ($errno) {
// fatal error. die it.
case E_USER_ERROR:
echo "<b>Error:</b> [$errno] $errstr<br />";
echo "Ending Script<br>";
// Fatal err. so mail to web master.
//error_log("Error: [$errno] $errstr", 1, "someone@example.com","From: webmaster@example.com");
die();
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; // no return (=null) is treated as true
}
//set error handler for E_USER_WARNING type only
$prevErrHandler = set_error_handler("customError"); // 2nd param can be E_USER_WARNING,..
$test = 3 ;
if ($test > 1)
{
// trigger err of type E_USER_WARNING. Above err handler(customError) comes into affect.
trigger_error("Value must be 1 or below", E_USER_NOTICE); // E_USER_WARNING / E_USER_ERROR / E_USER_NOTICE. Giving Error type is optional.
}
// Restore default err handler - user defined or built-in
restore_error_handler();
if ($test > 1)
{
// this same code as above will not use 'customError' handler now.
trigger_error("Value must be 2 or below", E_USER_WARNING);
}
/* E_USER_ERROR / E_USER_WARNING / E_USER_NOTICE.
E_USER_ERROR will halt exectution. */
?>
For logging error in log file, you need to use ini_set('log_errors', 'On'); on script or through php.ini and set the error log filename in php.ini or set the log file name at error_log() call (error_log($err, 3, 'error_log.txt');).
Related: JavaScript Error Handling for Beginners
PHP Parse Errors
Possibly Related posts:


