As of 2019 here is what I elaborated from the answers above and Guzzle docs to handle the exception, get the response body, status code, message and the other sometimes valuable response items.
try {
$result = theMethodMayThrowException();
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
var_dump($response->getStatusCode());
var_dump($response->getReasonPhrase());
var_dump((string) $response->getBody());
var_dump(json_decode((string) $response->getBody()));
var_dump($response->getHeaders());
var_dump($response->hasHeader('Content-Type'));
var_dump($response->getHeader('Content-Type')[0]);
}
}
Voila. You get the response's information in conveniently separated items.
Side Notes:
With catch
clause we catch the inheritance chain PHP root exception class
\Exception
as Guzzle custom exceptions extend it.
This approach may be useful for use cases where Guzzle is used under the hood like in Laravel or AWS API PHP SDK so you cannot catch the genuine Guzzle exception.
In this case, the exception class may not be the one mentioned in the Guzzle docs (e.g. GuzzleHttp\Exception\RequestException
as the root exception for Guzzle).
So you have to catch \Exception
instead but bear in mind it is still the Guzzle exception class instance.
Though use with care. Those wrappers may make Guzzle $e->getResponse()
object's genuine methods not available. In this case, you will have to look at the wrapper's actual exception source code and find out how to get status, message, etc. instead of using Guzzle $response
's methods.
If you call Guzzle directly yourself you can catch GuzzleHttp\Exception\RequestException
or any other one mentioned in their exceptions docs with respect to your use case conditions.