我正在迈出这一步:我的 PHP 脚本将全部优雅地失败!
至少,这就是我所希望的...`
我不想(实际上)在 try...catch
语句中包装每一行,所以我认为我最好的选择是为我的文件开头制作一个自定义错误处理程序.
我正在练习页面上对其进行测试:
function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
echo($imAFakeVariable);
这工作正常,返回:
Sorry, an error has occurred on line 17. The function that caused the error says Undefined variable: imAFakeVariable.
但是,此设置不适用于未定义的函数。
function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
imAFakeFunction();
返回:
Fatal error: Call to undefined function: imafakefunction() in /Library/WebServer/Documents/experimental/errorhandle.php on line 17
为什么我的自定义错误处理程序不能捕获未定义的函数?这会导致其他问题吗?
最佳答案
set_error_handler
设计用于处理代码错误:E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE
。这是因为 set_error_handler
是一种报告由 user 错误函数 trigger_error
抛出的错误的方法。
但是,我确实在手册中找到了可能对您有帮助的注释:
"The following error types cannot be handled with a user defined function:
E_ERROR
,E_PARSE
,E_CORE_ERROR
,E_CORE_WARNING
,E_COMPILE_ERROR
,E_COMPILE_WARNING
, and most ofE_STRICT
raised in the file whereset_error_handler()
is called."This is not exactly true.
set_error_handler()
can't handle them, butob_start()
can handle at leastE_ERROR
.<?php function error_handler($output) { $error = error_get_last(); $output = ""; foreach ($error as $info => $string) $output .= "{$info}: {$string}\n"; return $output; } ob_start('error_handler'); will_this_undefined_function_raise_an_error(); ?>
实际上,例如,这些错误应该在文件中以静默方式报告。希望您的项目中不会出现很多 E_PARSE
错误! :-)
至于一般的错误报告,坚持使用异常(我发现让它们与我的 MVC 系统结合很有帮助)。您可以构建一个非常通用的异常以通过按钮提供选项并添加大量描述以让用户知道哪里出了问题。
关于php - 如何在 PHP 中使用 set_error_handler 捕获未定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36621/