user2381982
user2381982

Reputation: 21

Do not log supressed PHP Warning

Is there any way to find out if this warning was supressed or not using the set_error_handler() function? The code is 2 for @somethingwrong() and somethingwrong(). But I don't want to log all warnings. For example some functions like gzuncompress() must be handled this way because I have no way to test for valid input data.

$handler = new errorHandler();
error_reporting(0);
set_error_handler(array($handler, 'handle'));
set_exception_handler(array($handler, 'exception'));
register_shutdown_function(array($handler, 'shutdown'));

class errorHandler
{
public function handle($code, $text, $file, $line)
{
    if (($code & (E_STRICT | E_NOTICE)) == 0)
        $this->log(...);
}

public function exception($exception)
{
    ...
}

public function shutdown()
{
    $e = error_get_last();
    if ($e !== NULL)
        $this->log($error);
}
}

// the errors
include('notexisting.file'); // should be logged
@gzuncompress('somenonsens'); // should not be logged

Upvotes: 1

Views: 171

Answers (2)

David Spector
David Spector

Reputation: 1671

I found a solution. Initially, I call

error_reporting(E_USER_ERROR);

This suppresses all errors except one, which I avoid raising myself, so it should never happen. I do this because I intercept all errors myself, reporting them in any of four ways (to screen, by email, to local log, to PHP log). I also do this to avoid an error reporting level of 0.

Then, in an error handler or shutdown function, I can detect the use of an at sign by the fact that it changes the error reporting level:

if (error_reporting() != E_USER_ERROR)
    return; // Ignore this error

Note that the effect of at sign changes between PHP version 7 and 8. I have not tested this with version 8.

Upvotes: 0

tomsv
tomsv

Reputation: 7277

Did you try it? I think if you use @ as in @gzuncompress you will not get a normal warning and you will also not have your errorhandler called.

Upvotes: 0

Related Questions