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 }
Why does this code work? According the PHP documentation at http://php.net/manual/en/function.set-error-handler.php "the following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING." Are these user defined warning created by you?
Nathan,
It catches E_NOTICE and E_WARNING.
Great! Thanks! It catches the warning messages apart from the default try and catch method!
In the PHP Manual, there is a discussion about how turning all errors into exceptions caught by a handler fails in the case of severity E_USER_NOTICE and the like, since this solution can't continue code execution.
My solution is simple: use errors and exceptions only when the code must stop executing. Use ordinary PHP features such as 'echo' or 'error_log" to report information to the user.