How to handle Guzzle exception and get Http Body?

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:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store