根据通知/警告停止脚本执行

2022-01-03 00:00:00 configuration php

是否可以在全球范围内根据通知/警告停止执行 PHP?

Is it possible to have PHP stop execution upon a notice/warning, globally?

我们运行的开发服务器上有很多站点,但希望迫使我们的开发人员修复这些警告/通知(或至少寻求帮助),而不是忽略并继续前进.

We run a development server with a lot of sites on, but want to force our developers to fix these warnings/notices (or ask for help with them at least) instead of ignoring and moving on.

推荐答案

是的,这是可能的.这个问题涉及如何处理 PHP 中的错误的更普遍的问题.您应该使用 set_error_handler<定义和注册自定义错误处理程序em>docs 自定义处理 PHP 错误.

Yes, it is possible. This question speaks to the more general issue of how to handle errors in PHP. You should define and register a custom error handler using set_error_handlerdocs to customize handling for PHP errors.

恕我直言,最好对任何 PHP 错误抛出异常并使用 try/catch 块来控制程序流程,但在这一点上存在不同意见.

IMHO it's best to throw an exception on any PHP error and use try/catch blocks to control program flow, but opinions differ on this point.

为了完成 OP 的既定目标,您可以执行以下操作:

To accomplish the OP's stated goal you might do something like:

function errHandle($errNo, $errStr, $errFile, $errLine) {
    $msg = "$errStr in $errFile on line $errLine";
    if ($errNo == E_NOTICE || $errNo == E_WARNING) {
        throw new ErrorException($msg, $errNo);
    } else {
        echo $msg;
    }
}

set_error_handler('errHandle');

上述代码将在任何时候引发 E_NOTICEE_WARNING 时抛出 ErrorException,从而有效地终止脚本输出(如果异常是t 抓住了).在 PHP 错误上抛出异常最好与并行异常处理策略结合(set_exception_handler) 以在生产环境中正常终止.

The above code will throw an ErrorException any time an E_NOTICE or E_WARNING is raised, effectively terminating script output (if the exception isn't caught). Throwing exceptions on PHP errors is best combined with a parallel exception handling strategy (set_exception_handler) to gracefully terminate in production environments.

请注意,上面的示例不会遵守 @ 错误抑制运算符.如果这对您很重要,只需使用 error_reporting() 函数添加一个检查,如下所示:

Note that the above example will not respect the @ error suppression operator. If this is important to you, simply add a check with the error_reporting() function as demonstrated here:

function errHandle($errNo, $errStr, $errFile, $errLine) {
    if (error_reporting() == 0) {
        // @ suppression used, don't worry about it
        return;
    }
    // handle error here
}

相关文章