Question

I have recently used Guzzle to scrape a URL, and this works fine when there are no errors.

If however there is for example a 404, let's say

$response = $client->get('http://www.google.com/test')->send();

The manual (Response Status Line) suggests the above code will then allow me to call

$response->isSuccessful();

But send() throws a ClientErrorResponseException when there is an error receiving the request. The exception thrown is as follows

Guzzle\Http\Exception\ClientErrorResponseException
Client error response
  [status code] 404
  [reason phrase] Not Found
  [url] http://www.google.com/test

So, catching that exception obviously prevents my application halting, but then means I don't have a response object on which to call the various isX methods.

Clearly catching the exception gives me the same answer as isSuccessful to some degree, but some of the other methods on the aforementioned manual page would also be useful to use.

What am I doing wrong?

Was it helpful?

Solution

You can specify ['exceptions' => FALSE] as a request option. See https://github.com/guzzle/guzzle/blob/master/docs/clients.rst#exceptions

Or, when you catch the exception, you can still get the response:

catch (\GuzzleHttp\Exception\ClientException $e) {
  $response = $e->getResponse();
}

http://guzzle3.readthedocs.org/http-client/client.html#exceptions

Kudos to both of the following for pointing this out on Github

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top