PHP: How to check for timeout exception in Guzzle 4?

纵饮孤独 提交于 2019-12-03 06:05:20

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();
});

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

The Exeption is generated here:

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
    );
}

while this is a private function, you have two options:

  • clone the entire file, give it a new name, use this instead of the CurlAdapter and throw another Exception than "AdapterException"
  • edit the file and throw another Exeption than "AdapterException" but in this case, your Guzzle is no longer maintainable.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!