首页 > 解决方案 > 使用 PHP/Laravel 捕获 cURL 错误

问题描述

对于我的 Laravel 应用程序,我使用 Goutte 包来抓取 DOM,它允许我使用 guzzle 设置。

$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
    'timeout' => 15,
));
$goutteClient->setClient($guzzleClient);

$crawler = $goutteClient->request('GET', 'https://www.google.com/');

我目前正在使用 guzzle 的timeout功能,它会返回这样的错误,例如,当客户端超时时:

cURL 错误 28:操作在 1009 毫秒后超时,收到 0 个字节(请参阅http://curl.haxx.se/libcurl/c/libcurl-errors.html

现在这很酷,但我实际上并不希望它返回一个 cURL 错误并停止我的程序。

我更喜欢这样的东西:

if (guzzle client timed out) {
    do this
} else {
    do that
}

我怎样才能做到这一点?

标签: phplaravelcurlguzzle

解决方案


弄清楚了。Guzzle 对请求有自己的错误处理。

来源:http ://docs.guzzlephp.org/en/stable/quickstart.html#exceptions

解决方案:

use GuzzleHttp\Exception\RequestException;

...

try {
    $crawler = $goutteClient->request('GET', 'https://www.google.com');
    $crawlerError = false;
} catch (RequestException $e) {
    $crawlerError = true;
}


if ($crawlerError == true) {
    do the thing
} else {
   do the other thing
}

推荐阅读