【问题标题】:Detecting error-control operator检测错误控制算子
【发布时间】:2010-11-20 00:19:55
【问题描述】:

请告诉我这是否正确。在我的错误处理程序中,我需要能够检测到 @error-control 运算符何时用于抑制错误,因为一些外部库(可悲的是)经常使用它。应该继续执行脚本,就像您不使用自定义错误处理程序一样。

当使用 at 符号时,PHP 临时将 error_reporting 设置为 0。因此,在脚本开始时,我们将 error_reporting 设置为除零以外的任何值——我们现在可以做一些漂亮的 IF/ELSE 魔术。为了避免在前端显示任何错误,我们还将 display_errors 设置为 0,这将覆盖 error_reporting(但我们仍然可以将其值用于魔术)。

<?php

ini_set('display_errors',0);
error_reporting(E_ALL);

function error_handler($errno, $errstr, $errfile, $errline)
{
    if (error_reporting()===0) return;
    else die();
}

set_error_handler('error_handler');

//This issues an error, but the handler will return and execution continues.
//Remove the at-sign and the script will die()
@file();

echo 'Execution continued, hooray.';
?>

所以.. 这里没有问题吗?除了外部库覆盖我的错误处理的那个..(有什么提示吗?)

【问题讨论】:

    标签: php error-handling


    【解决方案1】:

    考虑到你的脚本做了什么,以及@ operator manual page 上的一些用户注释,看来你正在做的事情还可以。

    例如,taras says

    我对@符号的含义感到困惑 实际上确实如此,经过几次 实验得出结论 以下:

    • 无论设置的错误处理程序是什么级别,都会调用 错误报告是否设置为 该语句以@

    • 开头
    • 由错误处理程序赋予不同的含义 错误级别。你可以让你的 自定义错误处理程序回显所有错误, 即使错误报告设置为 无。

    • 那么@ 运算符有什么作用呢?它临时设置错误报告 该行的级别为 0。如果那条线 触发错误,错误处理程序 仍然会被调用,但它会是 调用错误级别为 0

    set_error_handler 手册页似乎证实了这一点:

    需要特别注意的是,如果声明这个值将是 0 导致错误的原因是由 @error-control 运算符添加的。

    这里也有一些有用的用户注释;例如,this one(见代码开头)


    不过,如果您想要“禁用”@ 运算符的效果 (不确定我是否正确理解了这个问题;这可能对您有所帮助),以便能够得到错误在开发环境中的消息,您可以安装尖叫扩展(peclmanual

    如果你以正确的方式配置它,在你的 php.ini 中设置它(当然是在安装/加载扩展之后):

    scream.enabled = 1
    

    这个扩展只会禁用@操作符。


    这是一个例子(引用manual):

    <?php
    // Make sure errors will be shown
    ini_set('display_errors', true);
    error_reporting(E_ALL);
    
    // Disable scream - this is the default and produce an error
    ini_set('scream.enabled', false);
    echo "Opening http://example.com/not-existing-file\n";
    @fopen('http://example.com/not-existing-file', 'r');
    
    // Now enable scream and try again
    ini_set('scream.enabled', true);
    echo "Opening http://example.com/not-existing-file\n";
    @fopen('http://example.com/another-not-existing-file', 'r');
    ?>
    

    这将输出:

    Opening http://example.com/not-existing-file
    Opening http://example.com/not-existing-file
    
    Warning: fopen(http://example.com/another-not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14
    


    我不确定我是否会在生产服务器上使用这个扩展(我从不希望显示错误),但它在开发机器上非常有用,当使用旧代码时,在广泛使用 @ 运算符的应用程序/库上......

    【讨论】:

    • +1。这个确认是我所需要的。尖叫扩展似乎很有用,可能会检查一下。但在今天的情况下,我只是希望一个外部库能够做到这一点 - 就好像我的应用程序不存在一样。
    猜你喜欢
    • 2021-07-15
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2019-04-23
    相关资源
    最近更新 更多