|
|
2#

楼主 |
发表于 2007-10-4 22:31:43
|
只看该作者

表E给出一个简单例子:
表E
<?php
// define custom handler
set_error_handler('myHandler');
// custom handler code
function myHandler($code, $msg, $file, $line) {
echo "Just so you know, something went wrong at line $line of your script $file. The system says that the error code was $code, and the reason for the error was: $msg. Sorry about this!";
}
// generate a notice
echo $undefVar;
?>
当运行此脚本的时候,会出现下面的信息:
Just so you know, something went wrong at line 11 of your /dev/error1.php. The system says that the error code was 8, and the reason for the error was: Undefined variable: undefVar. Sorry about this!
此时,PHP的默认错误处理器被用户定义的myHandler()函数所取代,$undefVar变量被激活,PHP通知未定义变量的信息,此信息在运行时引擎产生,然后传递给myHandler()函数,同时错误发生的地址也传递给此函数。然后myHandler()函数输出友好信息解释错误。
注意:错误和致命错误很重要,它们会绕过自定义错误处理器,然后以PHP默认的错误处理机制进行显示。显示这些信息可使用前面讨论的标准error_reporting()函数进行控制。
例1:动态错误页面和e-mail警报
表F给出了另一个范例,当发生错误时,将动态产生HTML错误页面,并且通过e-mail向Web管理员进行报告。
表F
<?php
// define custom handler
set_error_handler('myHandler');
// custom handler code
function myHandler($code, $msg, $file, $line, $context) {
// print error page
echo "<html><head></head><body>";
echo "<h2 align=center>Error!</h2>";
echo "<font color=red size=+1>";
echo "An error occurred while processing your request. Please visit our <a href=http://www.domain.dom>home page</a> and try again.";
echo "</font>";
echo "</body></html>";
// email error to admin
$body = "$msg at $file ($line), timed at " . date ("d-M-Y h:i:s", mktime());
$body .= "\n\n" . print_r($context, TRUE);
mail ("webmaster@domain.dom", "Web site error", $body);
// halt execution of script
die();
}
// generate a notice
echo $undefVar;
?>
这里,自定义的错误处理器在遇到错误时动态产生HTML错误页面。此错误信息也能被e-mail信息捕获,然后通过PHP内置的mail()函数发送给管理员。
这里出现了myHandler()函数的一个新参数$context。这是myHandler()函数的第五个参数,是可选项。它包含了当前变量状态的快照。包括对管理员有用的上下文信息,有利于减少调试时间。
例2:自定义错误日志
表G给出了另一个例子,这个例子说明自定义错误处理器如何将详细的错误信息输入到文件。
表G
<?php
// define custom handler
set_error_handler('myHandler');
// custom handler code
function myHandler($code, $msg, $file, $line) {
// print error page
echo "<html><head></head><body>";
echo "<h2 align=center>Error!</h2>";
echo "<font color=red size=+1>";
echo "An error occurred while processing your request. Please visit our <a href=http://www.domain.dom>home page</a> and try again.";
echo "</font>";
echo "</body></html>";
// log error to file, with context
$logData = date("d-M-Y h:i:s", mktime()) . ", $code, $msg, $line, $file\n";
file_put_contents("web.log", $logData, FILE_APPEND);
// halt execution of script
die();
}
// generate a warning
echo is_float();
?>
与前面的例子相似,它也产生一个错误页面并且将错误数据输入到文件,以利于管理员进行查看。数据以CSV格式进行存储,并且有简单的数据分析和报告。请注意在本例和前面实例中,错误处理代码结束时调用die()函数,以确保脚本不再运行。
如上面的范例所示,自定义错误处理器允许以友好的方式处理PHP脚本错误。并且可以发挥自己的创造性,不过需要记住的是:任何灵活性的增加都伴随着开销和时间的增加。 |
|