当前位置:首页 > PHP > 正文内容

php将警告转换为异常

高老师5年前 (2020-10-31)PHP1071

有许多内置的PHP函数会生成通知或警告,提示您在发生问题时无法关闭,例如parse_ini_file和file_get_contents。一种常见的解决方案是使用@运算符禁止显示并通过error_get_last()函数获取警告信息:

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

更好的方法是使用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();

在这种情况下,我们注册我们自己的错误处理程序,该处理程序将每个通知,警告和错误转换为ErrorException,然后可以在其他地方捕获该错误。

但在php7以后官方会逐步统一万物皆异常,例如:

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

扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/175.html

分享给朋友:

“php将警告转换为异常” 的相关文章

 php抽象类和接口作用

php抽象类和接口作用

【一】.抽象类假设如下场景:团队准备开发某网站,表建好了,页面设计好了.A组负责开发底层数据库操作类(DB),B组负责调用DB类.但是此时A组发生了争执,MySQL? Oracle? DB2? sqlite?到底使用什么数据库?B组.... 进入漫长的等待.解决方法:A组和B组 先定1个数据库类的模...

php 开启错误提示,php 关闭错误提示

php 开启错误提示,php 关闭错误提示

开启错误提示代码:ini_set("display_errors", "On"); error_reporting(E_ALL | E_STRICT);关闭错误提示代码:error_reporting(E_ALL ^&n...

 php 判断是否post,php判断是否post提交,php 判断是否为post,php 判断get 还是post

php 判断是否post,php判断是否post提交,php 判断是否为post,php 判断get 还是post

if($_SERVER['REQUEST_METHOD'] == 'POST') { echo('This is  post '); } elseif ($_SERVER['...

php new class

php new class

<?php $member = new class {     public function getInfo()     {    ...

php执行慢原因查找

php执行慢原因查找

今天帮朋友查询wordpress执行超级慢的原因,特此记录开启fpm的慢日志,记录执行超过30秒的脚本request_slowlog_timeout = 30 slowlog = var/log/slow.log查看日志[23-May-2019 17...

php jsonp转json,php jsonp转数组,php jsonp转对象

php jsonp转json,php jsonp转数组,php jsonp转对象

将jsonp转为PHP数组和对象。/**  * jsonp转数组|Jsonp转json  * @param string $jsonp jsonp字符串  * @param bool $as...