在 Guzzle 中访问被拒绝的并发请求的响应

Access the response for rejected concurrent requests in Guzzle

我正在使用 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();

问题是我的一些请求 return 响应了 500 个 HTTP 响应,但仍然发送了一些内容(例如为什么会发生错误)。不幸的是,Guzzle 类 带有 500 个状态代码的 http 响应 'rejected',我似乎无法获得原始响应,因为被拒绝的函数中不存在该参数。

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

{
    xdebug: "..."
}

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

GuzzleHttp\Exception\ServerException: Server error: `GET http://example.com` resulted in a `500 Internal Server Error` response: {"failure_reason":"Useful message"} in [...stacktrace ...]

虽然这包含原始回复,但我无法轻易将其提取出来,因为它隐藏在 HTML 中,因此非常无用。我也不知道这是怎么设置的。

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

经过一番努力,我终于设法回答了我自己的问题。 $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