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:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response