PHP:如何检查 Guzzle 4 中的超时异常?

标签 php exception timeout guzzle

如果在请求期间发生错误,Guzzle 会抛出异常。不幸的是,似乎没有特定于超时的错误 - 这对我来说很重要,因为我知道这些偶尔会发生。我想重试相应的请求,并且需要能够判断错误是否因超时而发生。

来自docs :

// Timeout if a server does not return a response in 3.14 seconds.
$client->get('/delay/5', ['timeout' => 3.14]);
// PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\RequestException'

RequestException 在其message 属性中有信息:

"cURL error 28: Operation timed out after 3114 milliseconds with 0 bytes received"

所以我可以评估消息模式,但这感觉有点不对,因为这些消息将来很容易更改。

在使用 guzzle 4 时是否有更好/更稳定的方法来检查超时?

最佳答案

我有同样的问题,我已经通过停止事件的传播来解决它。您可以阅读更多相关信息 here .

use GuzzleHttp\Event\ErrorEvent;
use GuzzleHttp\Message\Response;

$client->getEmitter()->on('error', function(ErrorEvent $event) {
    $event->stopPropagation();
    $event->intercept(new Response(200));
    echo $event->getException()->getMessage();
});

在您的情况下,这将输出 cURL error 28: Operation timed out after 3114 milliseconds with 0 bytes received 而不会抛出 RequestException

关于PHP:如何检查 Guzzle 4 中的超时异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661591/

相关文章:

javascript - 重置超时的正确方法是什么?

python - 如何在等待响应时增加 AWS Sagemaker 调用超时

c# - SmtpClient 邮件发送超时

php - 根据选中的复选框更新 mysql 表

php - 获取用户发表的评论数量的最佳方式

c++ - 如果 delete[] p 失败会发生什么?

python - 更多 pythonic 方式来处理嵌套的 try... 除了 block ?

php - 在smarty模板系统中使用PHP从数据库中获取SUM

php - 如何让两个不同的文件夹从一个文件夹中获取资源?

java - Spring Controller Advice异常处理程序总是返回404