php - 如何在 PHP 中使用 set_error_handler 捕获未定义的函数

标签 php

我正在迈出这一步:我的 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 of E_STRICT raised in the file where set_error_handler() is called."

This is not exactly true. set_error_handler() can't handle them, but ob_start() can handle at least E_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/

相关文章:

php - 谷歌地图实现导致谷歌页面速度问题

php 视频和照片上传 : storing in database vs. uploading

php - 在 OctoberCMS 的 PHP 数据库中保存模型属性

php - 为什么 REST Response 没有结束执行?

php - SELECT 自定义字段和 LEFT JOIN 时的所有字段

php - 如何使用正则表达式从HTML获取所有YouTube iframe

php - Magento升级脚本不升级

php - 在用户输入上使用白名单

javascript - 为什么我的 PHP 和 Javascript 更改没有体现出来?

php - 在 PHP 中分解字符串