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.
Is this incorrect documentation or a bug or am I simply using Guzzle wrong?
In Guzzle 4.x, 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();
if ($response && $response->getStatusCode() == 406) {
// Do something with a 406 response here (as an example).
}
else {
throw $e;
}
}
Sorry I don't know enough about Guzzle 3.
You can get access to the response using $e->getResponse() in both Guzzle 3 and 4. You can also disable exceptions in Guzzle 3 using the "exceptions" request option: http://guzzle3.readthedocs.org/http-client/client.html#exceptions.
@pjcdawkins answer is correct but the link is broken.
It's still working for Guzzle v6 but it's not documented anymore.
But this test file gives the guarantee that this option is well supported.
The option http-errors is documented here and seams to do the same as expected.
This doc file will gives you very useful explanations about when and what kind of exceptions can be thrown.
Most helpful comment
In Guzzle 4.x, you can specify
['exceptions' => FALSE]as a request option. Seehttps://github.com/guzzle/guzzle/blob/master/docs/clients.rst#exceptions
Or, when you catch the exception, you can still get the response:
Sorry I don't know enough about Guzzle 3.