为什么会出现致命错误:未捕获异常'GuzzleHttp\Exception\ClientException',并显示消息'客户端错误:404'?

4

我尝试使用try catch捕获异常,但仍然出现了“致命错误:在C:\ OS \ OpenServer \ domains \ kinopoisk \ parser \ php \ vendor \ guzzlehttp \ guzzle \ src \ Middleware.php的消息中抛出未捕获的异常' GuzzleHttp \ Exception \ ClientException':69个客户端错误404”

 <?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();

我的代码有什么问题?

2个回答

6

我不确定,但是你只在这里捕获了 ClientException。尝试同时捕获 RequestException。从 Middleware.php:69 中的代码来看,这是使用的异常类,但如果你想捕获所有异常,那么你需要选择最抽象的异常类,应该是 RuntimeExceptionGuzzleException

尝试像这样:

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
    }
}

或者您可以尝试以下方法。
try {
    // your code here
} catch (ClientException $e) {
    // catches all ClientExceptions
} catch (RequestException $e) {
    // catches all RequestExceptions
}

希望能帮到您。

谢谢您的反馈,它帮助我了解了我的错误所在。我认为我不是真正理解了"$promise->wait()"的含义,因为当我在我的"foreache"中替换它时,一切都开始正常工作。同样,当我在"try catch"语句块中使用$promise->wait()时,它也能正常工作。 - TheMrbikus

0
<?php
  
  //some code
  
  try {
    $promise->wait();
  } catch (RequestException $e) {
    echo $e->getMessage();
  }

在guzzlehttp的requestAsync方法中,HTTP请求是在调用wait方法时启动的,而不是在调用requestAsync方法或then方法时启动的。因此,您需要在wait方法中添加try catch。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接