我尝试捕获异常,但我仍然收到"致命错误:未捕获的异常'GuzzleHttp''Exception''ClientException',并在C:''OS''OpenServer''domains''kinopoisk''parser''php''vendor''guzzlehttp''guzzle''src''Middleware.php: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();
我的代码中有什么问题?
我不确定,但你只在这里抓住ClientException
。也试着抓住RequestException
。查看Middleware.php:69
中使用的异常类的代码,但是如果要捕获所有异常,则需要选择最抽象的异常类,它应该是 RuntimeException
或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
}
希望有帮助。
<?php
//some code
try {
$promise->wait();
} catch (RequestException $e) {
echo $e->getMessage();
}
在 guzzlehttp requestasync 方法中,HTTP 请求是在调用 wait 方法时启动的,而不是在调用 requestasync 方法或 then 方法时启动的。因此,您需要在等待方法中添加 try catch