PHP:如何在Guzzle 4中检查超时异常? [英] PHP: How to check for timeout exception in Guzzle 4?

查看:597
本文介绍了PHP:如何在Guzzle 4中检查超时异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Guzzle throws an exception if an error occured during the request. Unfortunately, there does not seem to be an error specific to timeouts - which is important for me as I know that those can ocassionally occur. I'd like to retry the corresponding request and need to able to tell if the error occured due to a timeout.

来自文档

// 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"

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

So I could evaluate the message pattern but this feels kinda wrong, because those messages could easily be changed in the future.

更好/更稳定的方法在使用食尸鬼4时检查超时?

推荐答案

我遇到了同样的问题,我已通过停止事件的传播对其进行了修复。您可以在此处了解更多信息。

I had the same problem, I've fixed it with stopping an event’s propagation. You can read more about this 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错误28:3114之后操作超时接收到0字节的毫秒数而没有引发 RequestException

In your case this will output cURL error 28: Operation timed out after 3114 milliseconds with 0 bytes received without throwing an RequestException.

这篇关于PHP:如何在Guzzle 4中检查超时异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆