【问题标题】:Catching cURL errors with PHP/Laravel使用 PHP/Laravel 捕获 cURL 错误
【发布时间】:2019-08-20 18:56:30
【问题描述】:

对于我的 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
}

我该怎么做?

【问题讨论】:

    标签: php laravel curl guzzle


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      使用内置的 Laravel 异常类。

      解决方案:

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

      【讨论】:

      • 感谢这对我有用。 Laravel HTTP 客户端包装了 Guzzle,并且运行良好且方便,但不幸的是,它在没有服务器响应的情况下无法捕获连接失败。在某些情况下,我们确实需要知道服务器上的线程是正在运行还是失败,因此 ConnectionException 应该被视为一种 catch 返回。现在猜测我们将不得不写try { //try code } cat (Exception $long_useless_error) {//not succeeded, do something} 以使我们的逻辑完整。 p.s 不要忘记在控制器顶部引用use Exception;
      猜你喜欢
      • 2011-04-28
      • 2016-03-13
      • 1970-01-01
      • 2016-12-12
      • 2015-11-22
      • 2020-10-04
      • 2011-07-28
      相关资源
      最近更新 更多