簡體   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