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

php将警告转换为异常

高老师4年前 (2020-10-31)PHP1043

有许多内置的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跨域问题最佳解决方案

1、允许单个域名访问指定某域名(http://client.runoob.com)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加如下代码:header('Access-Control-Allow-Origin:http://client....

php curl 获取cookie

php curl 获取cookie

    为了实现注册机才写的教程,为了批量注册一个网站,注册带有验证码,幸好是文本验证码,但是有session验证,于是POST必须携带cookie。代码如下。<?php class  AutoCurl{    ...

php base64保存为图片偷懒版本

php base64保存为图片偷懒版本

<?php $base64_body = substr(strstr($_POST[base64],','),1); $data= base64_decode($base64_body); file_put_contents($_SERVER[&q...

PHP生成缩略图

PHP生成缩略图

//参数1  文件名    参数2  缩放比例  function   _thumb($_filename,$_percent){    ob_clean();...

php将html转为pdf,php将html页面导出pdf

php将html转为pdf,php将html页面导出pdf

首先下载wkhtmltox-0.12.4_linux-generic-amd64.tar.xz   (不要下载RPM包,依赖太多,需要x-server支持),并解压,执行测试运行正常tar wkhtmltox-0.12.4_linux-generic-amd64.tar.xzcd...

 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['...