簡體   English   中英

Multi Curl,錯誤處理

[英]Multi Curl, error handling

我正在使用 multi Curl 並且想知道如何處理錯誤。 我想檢查發生了哪個錯誤,如果它是一個錯誤,例如超出速率限制我想在延遲一段時間后再次抓取該鏈接(睡眠())。 我的問題:“是否有內置函數可以為我執行此操作,還是我需要將所有 Url 收集到一個數組中並再次運行它們?”

這就是我現在所擁有的:

<?php

$urls = array(  "https://API-URL.com",
                "https://API-URL.com",
                "https://API-URL.com",
                "https://API-URL.com",
                ...);

//create the multiple cURL handle
$mh = curl_multi_init();

//Number of elements in $urls
$nbr = count($urls);

// set URL and options
for($x = 0; $x < $nbr; $x++){

    // create both cURL resources
    $ch[$x] = curl_init();

    // set URL and other appropriate options
    curl_setopt($ch[$x], CURLOPT_URL, $urls[$x]);
    curl_setopt($ch[$x], CURLOPT_RETURNTRANSFER, true );
    curl_setopt($ch[$x], CURLOPT_SSL_VERIFYPEER, false);

    //add the two handles
    curl_multi_add_handle($mh,$ch[$x]);
}

//execute the handles
do {
    curl_multi_exec($mh, $running);
} while ($running);

for($x = 0; $x < $nbr; $x++){
    $result = curl_multi_getcontent($ch[$x]);

    $decoded = json_decode($result, true);

    //get info about the request
    $error = curl_getinfo($ch[$x], CURLINFO_HTTP_CODE);

    //error handling
    if($error != 200){

        $again[] = array("Url" => $urls[$x], "errornbr" => $error); 

    } else {

        // Here I do what ever I want with the data
    }

    curl_multi_remove_handle($mh, $ch[$x]);
    curl_close($ch[1]);
}

curl_multi_close($mh);
?>

在第二個for循環中,當您循環瀏覽各個curl處理程序以檢查每個curl處理程序返回了什么內容時,希望這種方法可以回答您的問題

foreach ($ch as $key => $h) {

//This code is actually checking for any error that may occur, whatever that 
//error is you can handle it in the if-part of the condition. and save those 
//urls to the array $again to call them on a later stage.

if (curl_errno($h)) {

//this is how you will get complete information what did happened to the 
//curl handler. And why did it fail. All the inforation will be stored in //error_info.

 $again[] = array("Url" =>curl_getinfo($h, CURLINFO_EFFECTIVE_URL), "error_info" => curl_getinfo($h)); 

}
else{

//here you will handle the success scenario for each curl handler.

$responses[$key] = ['data' => curl_multi_getcontent($h)];
}

//remove curl handler as you are doing in the loop

}

對於多個句柄有https://www.php.net/manual/en/function.curl-multi-info-read.php

所以錯誤檢查(假設 http 連接)應該如下所示:

while ($a = curl_multi_info_read($mh))
{
  if ($b = $a['result'])
  {
    echo curl_strerror($b);# CURLE_* error
  }
  elseif (!($b = curl_getinfo($a['handle'], CURLINFO_RESPONSE_CODE)))
  {
    echo 'connection failed';
  }
  elseif ($b !== 200)
  {
    echo 'HTTP status is not 200 OK';
  }
}

將此代碼視為現代 PHP 的偽代碼(我沒有測試這個確切的變體,但方案會起作用)。 在添加到“multi”句柄的“easy”句柄上調用curl_errno()將返回0 ,這不是錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM