【问题标题】:PHP: How to check for timeout exception in Guzzle 4?PHP:如何在 Guzzle 4 中检查超时异常?
【发布时间】:2014-10-28 23:22:02
【问题描述】:

如果请求期间发生错误,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 时是否有更好/更稳定的方法来检查超时?

【问题讨论】:

    标签: php exception timeout guzzle


    【解决方案1】:

    我遇到了同样的问题,我已经通过停止事件传播来解决它。你可以阅读更多关于这个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

    【讨论】:

    • 我需要删除$event->intercept(new Response(200)); 行,以免得到Call to a member function getMessage() on null。之后工作。谢谢!
    【解决方案2】:

    Exeption 在此处生成:

    https://github.com/guzzle/guzzle/blob/master/src/Adapter/Curl/CurlAdapter.php

    private function handleError(
        TransactionInterface $transaction,
        $info,
        $handle
    ) {
        $error = curl_error($handle);
        $this->releaseEasyHandle($handle);
        RequestEvents::emitError(
            $transaction,
            new AdapterException("cURL error {$info['curl_result']}: {$error}"),
            $info
        );
    }
    

    虽然这是一个私有函数,但您有两种选择:

    • 克隆整个文件,给它一个新名称,使用它而不是 CurlAdapter 并抛出另一个异常而不是“AdapterException”
    • 编辑文件并抛出除“AdapterException”之外的另一个异常,但在这种情况下,您的 Guzzle 不再可维护。

    【讨论】:

      猜你喜欢
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2020-07-15
      • 2023-04-08
      • 2011-04-11
      • 2019-10-19
      • 2010-11-02
      相关资源
      最近更新 更多