2

我尝试捕获异常,但我仍然收到“致命错误:未捕获的异常 'GuzzleHttp\Exception\ClientException' 并在 C:\OS\OpenServer\domains\kinopoisk\parser\php\vendor\guzzlehttp\ 中显示消息 'Client error: 404' 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();

我的代码有什么问题?

4

2 回答 2

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

或者您可以尝试以下方法

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

希望有帮助。

于 2015-11-22T11:39:54.043 回答
0
<?php
  
  //some code
  
  try {
    $promise->wait();
  } catch (RequestException $e) {
    echo $e->getMessage();
  }

在guzzlehttp requestasync 方法中,HTTP 请求是在调用wait 方法时发起的,而不是在调用requestasync 方法或then 方法时发起的。因此需要在wait方法中加入try catch

于 2021-02-23T01:58:28.287 回答