Turn warnings into exceptions

As I keep looking this up in other projects that I’ve written, I’m putting it here so I can find it more easily.

There are a number of built-in PHP functions that generate a notice or warning that you can’t turn off when something goes wrong, such as parse_ini_file and file_get_contents.

One common solution to this is to suppress using the @ operator:


$result = @file_get_contents($url);
if (false === $result) {
    // inspect error_get_last() to find out what went wrong
}

This doesn’t work when using Xdebug with the xdebug.scream set to 1 and its also inelegant and inefficient..

A better way is to use set_error_handler:

set_error_handler(function ($severity, $message, $file, $line) {
    throw new \ErrorException($message, $severity, $severity, $file, $line);
});
 
$result = file_get_contents($url);
 
restore_error_handler();

In this case, we register our own error handler that converts every notice, warning and error into an ErrorException that can then be caught elsewhere. We then call the PHP function of interest and immediately call restore_error_handler to put back the one we had earlier.

Interestingly, in PHP7, we can expect to see exceptions in the engine itself which should allow us to solve this problem like this:

try {
    $result = file_get_contents($url);
} catch (EngineException $e) {
    // do something with $e
}
备注:


Turn warnings into exceptions

相关文档

评论0条