简体   繁体   English

使用 PHP/Laravel 捕获 cURL 错误

[英]Catching cURL errors with PHP/Laravel

For my Laravel application, I use the Goutte package to crawl DOMs, which allows me to use guzzle settings.对于我的 Laravel 应用程序,我使用 Goutte 包来抓取 DOM,这允许我使用 guzzle 设置。

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

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

I'm currently using guzzle's timeout feature, which will return an error like this, for example, when the client times out:我目前正在使用 guzzle 的timeout功能,它会返回这样的错误,例如,当客户端超时时:

cURL error 28: Operation timed out after 1009 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html ) cURL 错误 28:操作在 1009 毫秒后超时,收到 0 个字节(参见http://curl.haxx.se/libcurl/c/libcurl-errors.html

Now this is cool and all, but I don't actually want it to return a cURL error and stop my program.现在这很酷,但我实际上并不希望它返回 cURL 错误并停止我的程序。

I'd prefer something like this:我更喜欢这样的事情:

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

How can I do this?我怎样才能做到这一点?

Use the inbuilt Laravel Exception class.使用内置的 Laravel Exception 类。

Solution:解决方案:

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

Figured it out.弄清楚了。 Guzzle has its own error handling for requests. Guzzle 有自己的请求错误处理。

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

Solution:解决方案:

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