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 errorsGuzzleHttp\Exception\ServerException
: for 5xx level errorsGuzzleHttp\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();
}