为什么我会收到致命错误:未捕获的异常' GuzzleHttp \ Exception \ ClientException'消息'客户端错误:404'?

时间:2015-11-22 11:20:56

标签: php guzzle guzzle6

我尝试捕获异常,但我仍然得到"致命错误:未捕获异常' GuzzleHttp \ Exception \ ClientException'消息'客户端错误:404'在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();

我的代码有什么问题?

2 个答案:

答案 0 :(得分:4)

我不确定,但你只是在这里捕捉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
}

希望有所帮助。

答案 1 :(得分:0)

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

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