在通知/警告后停止脚本执行 [英] Stop script execution upon notice/warning

查看:165
本文介绍了在通知/警告后停止脚本执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在全局通知/警告后停止执行PHP?

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

例如。对于服务器上的所有网站。

Eg. for all sites on the server.

我们运行的开发服务器上有很多网站,但是希望强制我们的开发人员修复这些警告/通知帮助他们至少)而不是忽略和继续。

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 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.

IMHO最好抛出异常对任何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的声明目标,你可能会做: / p>

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');

上述代码会抛出一个 ErrorException 时间a E_NOTICE E_WARNING ,有效终止脚本输出(如果未捕获到异常)。对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
}

这篇关于在通知/警告后停止脚本执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆