为什么我收到致命错误:未捕获的异常 'GuzzleHttp\Exception\ClientException' 并显示消息 'Client error: 404'?

The*_*kus 2 php guzzle guzzle6

我尝试捕获异常,但我仍然收到“致命错误:未捕获的异常 'GuzzleHttp\Exception\ClientException' 和消息 'Client error: 404' in C:\OS\OpenServer\domains\kinopoisk\parser\php\vendor\guzzlehttp\狂饮\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();
Run Code Online (Sandbox Code Playgroud)

我的代码有什么问题?

Gui*_*ing 6

我不确定,但你ClientException只在这里捕捉。也试着抓住RequestException。看里面的代码Middleware.php:69就是使用的异常类,但是如果你想捕获所有的异常,那么你需要去寻找最抽象的异常类,应该是 RuntimeExceptionor GuzzleException

尝试这样的事情:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以尝试以下方法

try {
    // your code here
} catch (ClientException $e) {
    // catches all ClientExceptions
} catch (RequestException $e) {
    // catches all RequestExceptions
}
Run Code Online (Sandbox Code Playgroud)

希望有帮助。