Handle Guzzle exception and get HTTP body

Guzzle 6.x Per the docs, the exception types you may need to catch are: GuzzleHttp\Exception\ClientException for 400-level errors GuzzleHttp\Exception\ServerException for 500-level errors GuzzleHttp\Exception\BadResponseException for both (it’s their superclass) Code to handle such errors thus now looks something like this: $client = new GuzzleHttp\Client; try { $client->get(‘http://google.com/nosuchpage’); } catch (GuzzleHttp\Exception\ClientException $e) { $response = $e->getResponse(); $responseBodyAsString … Read more

Guzzle: handle 400 bad request

As written in Guzzle official documentation: http://guzzle.readthedocs.org/en/latest/quickstart.html A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the exceptions request option is set to true For correct error handling I would use this code: use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; try { $response = $client->get(YOUR_URL, [ ‘connect_timeout’ => 10 ]); // Here the code for successful request } … Read more

Catching exceptions from Guzzle

Depending on your project, disabling exceptions for guzzle might be necessary. Sometimes coding rules disallow exceptions for flow control. You can disable exceptions for Guzzle 3 like this: $client = new \Guzzle\Http\Client($httpBase, array( ‘request.options’ => array( ‘exceptions’ => false, ) )); This does not disable curl exceptions for something like timeouts, but now you can … Read more

Guzzlehttp – How get the body of a response from Guzzle 6?

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator: $contents = (string) $response->getBody(); You can also do it with $contents = $response->getBody()->getContents(); The difference between the two approaches is that … Read more