How to handle Guzzle exception and get Http Body?

 

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:

留言

這個網誌中的熱門文章

什麼是QEMU ? 什麼是KVM ? 什麼是QEMU-KVM?

[Mac OSX] 如何關閉開機啟動的應用程式?