在Guzzle

时间:2016-10-13 07:52:27

标签: guzzle guzzle6

我正在使用Guzzle并发请求工具: http://docs.guzzlephp.org/en/latest/quickstart.html#concurrent-requests

我的代码类似于示例代码:

use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

$client = new Client();

$requests = function ($total) {
    $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
    for ($i = 0; $i < $total; $i++) {
        yield new Request('GET', $uri);
    }
};

$pool = new Pool($client, $requests(100), [
    'concurrency' => 5,
    'fulfilled' => function ($response, $index) {
        // this is delivered each successful response
    },
    'rejected' => function ($reason, $index) {
        // this is delivered each failed request
    },
]);

// Initiate the transfers and create a promise
$promise = $pool->promise();

// Force the pool of requests to complete.
$promise->wait();

问题是我的一些请求返回了500个HTTP响应的响应,但仍然发送了一些内容(例如,错误发生的原因)。不幸的是,Guzzle将具有500个状态代码的http响应归类为“拒绝”,并且我似乎无法获得原始响应,因为该参数在被拒绝的函数中不存在。

但我可以访问$reason。在我的例子中,它包含一个像这样的JSON:

{
    xdebug: "..."
}

xdebug属性包含HTML作为字符串,如下所示:

  

GuzzleHttp \ Exception \ ServerException:服务器错误:`GET   http://example.com`导致了“500内部服务器错误”   回复:{&#34; failure_reason&#34;:&#34;有用的信息&#34;}在[... stacktrace ...]

虽然这包含原始响应,但我无法轻易将其隐藏在HTML中,因此非常无用。我也不知道这是如何设置的。

因此,我的问题是,如何访问被拒绝的并发请求的响应?

1 个答案:

答案 0 :(得分:11)

经过一番努力,我终于设法回答了我自己的问题。 $reasonGuzzleException

因此我们可以检查它是什么类型的异常并执行适当的逻辑:

[
    ...,
    'rejected' => function ($reason, $index) {
        if ($reason instanceof GuzzleHttp\Exception\ClientException) {
            $body = $reason->getResponse()->getBody();
        }
    },
]

请注意,并非所有GuzzleException都有响应。有关详细信息,请参阅http://docs.guzzlephp.org/en/latest/quickstart.html#exceptions

相关问题