@ error suppression operator and set_error_handler

浪子不回头ぞ 提交于 2019-12-04 22:45:31

The @ operator temporarily sets error_reporting to 0, so you can test the value of error_reporting in your error handler:

if (ini_get('error_reporting') == 0) {
    return;
}

Or even better, log only error types that are in error_reporting:

$error_reporting = ini_get('error_reporting');

if ( !($error_reporting & $errno) ) {
    return;
}

Also take a look at the log_errors and error_log options, for automatically logging errors to a file or to syslog.

Solution that also works for PHP 7

According to the PHP docs:

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

Source: http://php.net/manual/en/language.operators.errorcontrol.php

So you can use the following code in your error handler:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    if (error_reporting() == 0) {
        /// @ sign temporary disabled error reporting
        return;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

You should actually avoid usage of @ operator. First of all, it is slow, and I would as far as to call it harmful.

What you should have instead is in php.ini file have two line:

error_repoting = E_ALL | E_STRICT
display_errors = Off

... or , if you do not have access to the php.ini file , then at the top of index.php (or any other bootstrap file) you should add :

error_reporting( E_ALL | E_STRICT );
ini_set('display_errors', 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!