php - 使用 PHP/Laravel 捕获 cURL 错误
问题描述
对于我的 Laravel 应用程序,我使用 Goutte 包来抓取 DOM,它允许我使用 guzzle 设置。
$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
'timeout' => 15,
));
$goutteClient->setClient($guzzleClient);
$crawler = $goutteClient->request('GET', 'https://www.google.com/');
我目前正在使用 guzzle 的timeout
功能,它会返回这样的错误,例如,当客户端超时时:
cURL 错误 28:操作在 1009 毫秒后超时,收到 0 个字节(请参阅http://curl.haxx.se/libcurl/c/libcurl-errors.html)
现在这很酷,但我实际上并不希望它返回一个 cURL 错误并停止我的程序。
我更喜欢这样的东西:
if (guzzle client timed out) {
do this
} else {
do that
}
我怎样才能做到这一点?
解决方案
弄清楚了。Guzzle 对请求有自己的错误处理。
来源:http ://docs.guzzlephp.org/en/stable/quickstart.html#exceptions
解决方案:
use GuzzleHttp\Exception\RequestException;
...
try {
$crawler = $goutteClient->request('GET', 'https://www.google.com');
$crawlerError = false;
} catch (RequestException $e) {
$crawlerError = true;
}
if ($crawlerError == true) {
do the thing
} else {
do the other thing
}
推荐阅读
- javascript - 如何比较数组中的对象并输出不匹配的对象
- python - 返回函数不保存值,然后你调用它说变量未定义的变量
- c# - Web API 返回空字符串不是预期的数据,状态码为 200
- java - 如何在运行时将属性添加到 Spring Boot 应用程序上下文
- html - 具有 HTML 3.2 文档类型的网页上的小书签中的错误
- javascript - 如何在Javascript中base64字符串中第一次出现逗号之前删除所有内容?
- sql - 如何在 Laravel 中将数据传递给 SQL 查询?
- reactjs - MUI 失败的道具类型:提供给 `ForwardRef(Link)` 的价值 `#ff9800` 的无效道具`color`,
- bash - 在 bash 脚本中使用带有特殊字符密码的 cURL 发送电子邮件
- php - 解析错误:语法错误,第 97 行 /home/ROOTNAME/public_html/wp-admin/index.php 中的意外“内容”(T_STRING),预期“)”