How to handle Guzzle exception and get Http Body?

hosomikai
1 min readSep 9, 2020
Photo by Taylor Vick on Unsplash

Guzzle 3.x

use Guzzle\Http\Exception\ClientErrorResponseException;

...

try {
$response = $request->send();
} catch (ClientErrorResponseException $exception) {
$responseBody = $exception->getResponse()->getBody(true);
}

getBody 傳入參數 true 表示你想要將 response body 轉成字串,
如果沒有將會回傳 Guzzle\Http\EntityBody 的 instance。

Guzzle 6.x

你可能會需要catch的 exception 類型有:

  • GuzzleHttp\Exception\ClientException : for 4xx level errors
  • GuzzleHttp\Exception\ServerException : for 5xx level errors
  • GuzzleHttp\Exception\BadResponseException : for both (superclass)
$client = new GuzzleHttp\Client;try {
$client->get("{$yourRequestUrl}");
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}

Reference:

--

--