[thelist] how to automatically trigger custom php error handling
sbeam
sbeam at onsetcorps.net
Fri Jan 14 13:47:23 CST 2005
On Friday 14 January 2005 01:11 pm, Sarah Sweeney wrote:
> I've kept an old thelist message kicking around in my inbox for a
while,
> meaning to make use of it; I finally got around to it today. It was a
> tip about error handling in PHP. My question is, if I set up a custom
> error handler using set_error_handler(), will it only be called if I
> also use trigger_error(), die(), or exit(), or will it be called any
and
> every time an error occurs?
Your handler will be called on trigger_error() and any other time an
error is generated as per your error_reporting() setting
The beauty of it is, errors come in many flavors
http://us2.php.net/manual/en/ref.errorfunc.php#errorfunc.constants
so you look at the error code in your handler and decide what to do, if
anything (you might ignore E_NOTICE for instance - but send an email
about E_WARNING)
It won't be called on die()/exit() - they kill the execution dead in its
tracks so your handler is never invoked. So don't use them anymore, use
trigger_error() (also gives you a chance to close filehandles, remove
locks, do database commits, etc. before you bail out)
Of course in PHP5 you won't need trigger_error() at all, you have
try{...}catch{...}
a basic error handler:
function my_error_handler ($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_ERROR:
case E_USER_ERROR:
echo error_format("<b>Sorry. An internal error occurred
and your request could not be processed.
Please let the <a
href=\"mailto:".EMAIL_ADMIN."\">webmaster</a> know or try
again later.", "#cc3333");
$smarty->display('site_footer.tpl');
mail_error_alert ($errno, $errstr, $errfile, $errline);
exit -1;
case E_WARNING:
case E_USER_WARNING:
echo error_format("<b>Warning<b> An internal error may have
occurred on this transaction.
Please let the <a
href=\"mailto:".EMAIL_ADMIN."\">webmaster</a>
know or try again later.");
mail_error_alert ($errno, $errstr, $errfile, $errline);
// note, no exit(), just keep on truckin'
break;
default:
printf(" [%s: '%s' at line %s of %s]",
isset($ERRORTYPES[$errno])? $ERRORTYPES[$errno] :
"UNKNOWN ERROR",
htmlentities($errstr),
$errline,
$errfile);
}
}
set_error_handler ('my_error_handler');
... time passes ...
if ($puddingRequest and !$meat) {
trigger_error("You can't have your pudding
if you don't eat your meat", E_USER_ERROR);
}
--
# S Beam - Web App Dev Servs
# http://www.onsetcorps.net/
More information about the thelist
mailing list