Why I get Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: 404'?

17,575

I am not sure, but you are catching ClientException only here. Try to catch RequestException, too. Looking at the code in Middleware.php:69 that is the exception class used, but if you want to catch all exceptions, then you need to go for the most abstract exception class, which should be RuntimeException or GuzzleException.

Try something like this:

try {
    // your code here
} catch (RuntimeException $e) {
    // catches all kinds of RuntimeExceptions
    if ($e instanceof ClientException) {
        // catch your ClientExceptions
    } else if ($e instanceof RequestException) {
        // catch your RequestExceptions
    }
}

or you can try following approach

try {
    // your code here
} catch (ClientException $e) {
    // catches all ClientExceptions
} catch (RequestException $e) {
    // catches all RequestExceptions
}

Hope that helps.

Share:
17,575
TheMrbikus
Author by

TheMrbikus

Updated on June 07, 2022

Comments

  • TheMrbikus
    TheMrbikus almost 2 years

    I try catch exception, but i still get "Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: 404' in C:\OS\OpenServer\domains\kinopoisk\parser\php\vendor\guzzlehttp\guzzle\src\Middleware.php:69"

     <?php
    
        ini_set('display_errors', 'on');
        error_reporting(E_ALL);
        set_time_limit(0);
    
        require "vendor/autoload.php";
    
        use GuzzleHttp\Client;
        use Psr\Http\Message\ResponseInterface;
        use GuzzleHttp\Exception\RequestException;
        use GuzzleHttp\Exception\ClientException;
    
        $filmsUrl = [297, 298];
    
        $urlIterator = new ArrayObject($filmsUrl);
    
        $client = new Client([
            'base_uri' => 'http://example.com',
            'cookies' => true,
        ]);
    
        foreach ($urlIterator->getIterator() as $key => $value) {
            try {
                $promise = $client->requestAsync('GET', 'post/' . $value, [
                    'proxy' => [
                        'http'  => 'tcp://216.190.97.3:3128'
                    ]
                ]);
    
                $promise->then(
                    function (ResponseInterface $res) {
                        echo $res->getStatusCode() . "\n";
                    },
                    function (RequestException $e) {
                        echo $e->getMessage() . "\n";
                        echo $e->getRequest()->getMethod();
                    }
                );
            } catch (ClientException $e) {
                echo $e->getMessage() . "\n";
                echo $e->getRequest()->getMethod();
            }
        }
        $promise->wait();
    

    What wrong in my code?