How do you handle client error in Guzzle?

You can easily handle client errors in Guzzle by catching the thrown exceptions . You can either catch the RequestException and it should cover most of the exceptions or you can catch the more specific ClientException which covers only the client exceptions such as 4xx status codes.

Here is an example of some code that results in a 404 Not Found exception that is handled by catching ClientException in Guzzle:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

$client = new Client();

try {
    $response = $client->get('https://httpbin.org/status/404');
    // Process response normally...
} catch (ClientException $e) {
    // An exception was raised but there is an HTTP response body
    // with the exception (in case of 404 and similar errors)
    $response = $e->getResponse();
    $responseBodyAsString = $response->getBody()->getContents();
    echo $response->getStatusCode() . PHP_EOL;
    echo $responseBodyAsString;
}

// Output:
// 404

You can read more about various exceptions thrown by Guzzle in the official docs .

Related Guzzle web scraping questions: