1. 云栖社区>
  2. PHP教程>
  3. 正文

Turn warnings into exceptions

作者:用户 来源:互联网 时间:2017-12-01 20:37:30

Turn warnings into exceptions - 摘要: 本文讲的是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

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 asparse_ini_fileandfile_get_contents.

One common solution to this is to suppress using [email protected]:

$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 useset_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 anErrorExceptionthat can then be caught elsewhere. We then call the PHP function of interest and immediately callrestore_error_handlerto put back the one we had earlier.

Interestingly, in PHP7, we can expect to seeexceptions in the engine itselfwhich should allow us to solve this problem like this:

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

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。