使用 PHP/Laravel 捕获 cURL 错误

Catching cURL errors with PHP/Laravel

对于我的 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 功能,这将 return 出现这样的错误,例如,当客户端超时时:

cURL error 28: Operation timed out after 1009 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

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

我更喜欢这样的东西:

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

我该怎么做?

想通了。 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
}

使用内置 Laravel 异常 class。

解决方案:

<?php

namespace App\Http\Controllers;

use Exception;

class MyController extends Controller
{
    public function index()
    {
        try
        {
            $crawler = $goutteClient->request('GET', 'https://www.google.com');
        }
        catch(Exception $e)
        {
            logger()->error('Goutte client error ' . $e->getMessage());
        }
    }
}