Reading the error response body when Guzzle throws an exception
GuzzleHttp\Exception\ClientExceptionShort answer
Guzzle throws ClientException for 4xx and ServerException for 5xx. The body is not on the exception itself: call getResponse() on it, then cast getBody() to a string. Network failures throw ConnectException, which has no response at all. To skip exceptions for HTTP errors, set http_errors to false.
Fix it fast
1Find out which cause you have
Catch the exception classes from most specific to least specific and print which one fired. The class tells you whether a response exists.
<?php use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ServerException; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\TransferException; try { $client->request('GET', 'https://api.example.com/users'); } catch (ClientException | ServerException $e) { echo get_class($e), ' with a response', PHP_EOL; } catch (ConnectException $e) { echo 'no response: ', $e->getMessage(), PHP_EOL; } catch (TransferException $e) { echo get_class($e), PHP_EOL; }2Match what you see, then jump to its fix
- 1
You call something on the exception expecting the body, or you only print getMessage() and see a truncated line.The body lives on the response, not on the exceptionFix - 2
Every 4xx or 5xx jumps to catch, even though the API uses 4xx codes for normal outcomes such as validation errors.You catch an HTTP error as an exception when you want to handle it as a normal responseFix - 3
getResponse() is null and the call on it crashes, or the exception class is ConnectException or TransferException.The failure was a network error, so there is no response to readFix - 4
The first echo shows the error body, a second read of the same body returns an empty string.The body stream reads back empty on the second readFix
- 1
What does the error look like?
GuzzleHttp\Exception\ClientExceptionGuzzleHttp\Exception\ServerExceptionGuzzleHttp\Exception\ConnectException
Cause 1 of 4
The body lives on the response, not on the exception
1Check
ClientException (4xx) and ServerException (5xx) come from the request exception branch of Guzzle's hierarchy, and that branch carries the request and the response. The message is only a short summary.
} catch (ClientException $e) {
echo $e->getResponse()->getStatusCode();
}2Fix
Take the response from the exception, then cast its body stream to a string.
try {
$client->request('POST', '/orders', ['json' => $payload]);
} catch (ClientException | ServerException $e) {
$response = $e->getResponse();
$status = $response->getStatusCode();
$body = (string) $response->getBody();
$data = json_decode($body, true);
}3Verify
Trigger a request that returns 404 and print the status and the body.
echo $status, ' ', $body;Confirmed by docs.guzzlephp.org
Cause 2 of 4
You catch an HTTP error as an exception when you want to handle it as a normal response
1Check
By default the http_errors request option is true, so Guzzle converts 4xx and 5xx responses into exceptions.
grep -rn "http_errors" src/ app/2Fix
Turn the option off for that client or that request. Then every response comes back as a normal object and you branch on the status code. Connection failures still throw.
$response = $client->request('GET', '/status/500', ['http_errors' => false]);
if ($response->getStatusCode() >= 400) {
$error = (string) $response->getBody();
}3Verify
A request that returns 500 now gives you a response, not an exception.
echo $response->getStatusCode();Confirmed by docs.guzzlephp.org
Cause 3 of 4
The failure was a network error, so there is no response to read
1Check
ConnectException is a networking error: DNS, refused connection, connect timeout. It sits under TransferException, outside the branch that holds responses. The same goes for a request that hits the timeout option.
} catch (ConnectException $e) {
echo get_class($e), ': ', $e->getMessage();
}2Fix
Handle ConnectException in its own catch block, and set explicit timeouts so a dead host fails fast. Catch TransferException last as the general fallback.
$client = new GuzzleHttp\Client([
'connect_timeout' => 5,
'timeout' => 15,
]);3Verify
Point the client at a closed port and confirm the ConnectException block runs, not the ClientException one.
$client->request('GET', 'http://127.0.0.1:9');Confirmed by docs.guzzlephp.org
Cause 4 of 4
The body stream reads back empty on the second read
1Check
The body is a stream. getContents() returns the remaining data from the current position, so after one full read there is nothing left. Casting the stream to a string is the documented way to get it as text.
$stream = $e->getResponse()->getBody();
var_dump($stream->tell(), $stream->getSize());2Fix
Read it once into a variable and reuse the variable for logging and for decoding.
$body = (string) $e->getResponse()->getBody();
error_log($body);
$data = json_decode($body, true);3Verify
Log and decode both work from the same variable.
var_dump(strlen($body), is_array($data));Confirmed by docs.guzzlephp.org
How do I stop it coming back?
- Catch ClientException and ServerException (or RequestException) before the general TransferException, and handle ConnectException separately.
- Set connect_timeout and timeout on the client; the default waits without a limit.
- Read the body into a variable once and pass that variable around, not the stream.
- Log the status code together with the body so the API's own error message is not lost.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix