繁体   English   中英

使用 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功能,它会返回这样的错误,例如,当客户端超时时:

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

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

我更喜欢这样的事情:

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

我怎样才能做到这一点?

使用内置的 Laravel Exception 类。

解决方案:

<?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());
        }
    }
}

弄清楚了。 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM