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

php将警告转换为异常

高老师6年前 (2020-10-31)PHP1165

有许多内置的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将警告转换为异常” 的相关文章

cookie中文乱码,GBK下

cookie中文乱码,GBK下

上家公司开发医院挂号系统,系统采用GBK编码。ajax发送的中文用户名让PHP保存为cookie出现乱码的解决方案。1.Javascript变量var user=document.getElementById('user').innerText; user=escape(u...

 php调用.net的dll文件,php调用.net dll

php调用.net的dll文件,php调用.net dll

本篇文章不是讲解如何用.net开发自己的dll然后PHP通过com调用。主要记录PHP官方支持的DOTNET 基本语法如下:$obj = new DOTNET("assembly", "classname")a...

php使用swoole扩展推送消息

php使用swoole扩展推送消息

通过http推送消息给socket,socket服务再向客户端推送<?php /*  * Socket推送  * 请用守护进程方式启动php msgservice.php &   (socket只...

php  while  true  cpu占用100%

php while true cpu占用100%

在编写多进程的实例中我在每个进程中使用如下代码://调用等待信号的处理器 while (true) {     pcntl_signal_dispatch(); }开启5个进程,cpu直接100%修正之后的代码://调用等待信号的处理器 while&...

php执行慢原因查找

php执行慢原因查找

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

php定义常量数组

php定义常量数组

<?php //php7+ define('CONFIG', [     'MYSQL' => '127.0.0.1',     ...