I would like to handle errors from Guzzle when the server returns 4xx and 5xx status codes. I make a request like this:
$client = $this->getGuzzleClient(); $request = $client->post($url, $headers, $value); try { $response = $request->send(); return $response->getBody(); } catch (Exception $e) { // How can I get the response body? }
$e->getMessage
returns code info but not the body of the HTTP response. How can I get the response body?
Answer
Guzzle 3.x
Per the docs, you can catch the appropriate exception type (ClientErrorResponseException
for 4xx errors) and call its getResponse()
method to get the response object, then call getBody()
on that:
use GuzzleHttpExceptionClientErrorResponseException; ... try { $response = $request->send(); } catch (ClientErrorResponseException $exception) { $responseBody = $exception->getResponse()->getBody(true); }
Passing true
to the getBody
function indicates that you want to get the response body as a string. Otherwise you will get it as instance of class GuzzleHttpEntityBody
.