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

php将警告转换为异常

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

有许多内置的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生成微信分享需要的signature签名

PHP生成微信分享需要的signature签名

因为一个TP项目中客户需要全部网页分享支持自定义图片和描述信息,于是自己封装了下 //share()微信分享链接 //参数1 appid //参数2 appsert //参数3 nonceStr随机码 //参数4 timestamp时间戳 public&nb...

PHP可变变量的作用

PHP可变变量的作用

<!doctype html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <bod...

php非对称加密

php非对称加密

先在centos安装openssl,然后开始://生成私钥openssl genrsa -out rsa_private_key.pem 1024//生成公钥openssl rsa -in rsa_private_key.pem&...

php创建webservice,php搭建webservice,php编写webservice

php创建webservice,php搭建webservice,php编写webservice

第一步:服务端文件<?php $wsdlfile='webservice.wsdl'; ini_set('soap.wsdl_cache_enabled','0');    //关闭WSDL缓存 //001...

 php mysql 行锁,php mysql 行级锁,php mysql 行锁定

php mysql 行锁,php mysql 行级锁,php mysql 行锁定

应用场景:PHP模拟购买,商品数量大于0才能购买常见代码:<?php //连接数据库 $con=mysqli_connect("localhost","ihuohuo","927464cy","ihuohuo");...

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