2017-07-14 109 views
0

即時通訊創建一個服務,並在這個服務即時通訊從一個API獲取一些數據,它工作正常,但現在我需要處理一些HTTP請求,其中之一是404,因爲有時數據即時嘗試檢索沒有找到。處理Http請求找不到

我從我服務的方法是:

public function getAllGamesFromDate($date = "2017-08-09", $tournament = "123") 
    { 

     $api = file_get_contents($this->url."schedules/".$date."/schedule.json?api_key=".$this->api_key); 

     $result = collect(json_decode($api, true))->toArray(); 

     $data = []; 



     foreach ($result['events'] as $event){ 
      if($event['id'] == $tournament){ 
       array_push($data,$event); 
      } 
     } 

     return response($data); 
    } 

當沒有數據,因爲我不是處理錯誤,我得到這個錯誤:

ErrorException in MyService.php line 32: 
file_get_contents(https://api.url...): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found 

什麼是處理這個問題的最好辦法錯誤類型?

+0

可能重複[file \ _get \ _contents()如何修復錯誤「無法打開流」,「沒有這樣的文件」](https://stackoverflow.com/questions/20562368/file-get-contents-如何修復錯誤失敗打開流沒有這樣的文件) –

回答

2

創建助手此功能:

function get_http_response_code($url) { 
    $headers = get_headers($url); 
    return substr($headers[0], 9, 3); 
} 

並檢查是否get_http_response_code($this->url."schedules/".$date."/schedule.json?api_key=".$this->api_key)!= 200

-1

難道你不能簡單地在file_get_contents周圍使用try/catch塊嗎?

try { 
    $api = file_get_contents($this->url."schedules/".$date."/schedule.json?api_key=".$this->api_key); 
{ catch (Exception $e) { 
    echo $e->getMessage(); 
} 

而且你還可以通過把一個@呼叫前面的file_get_contents()抑制警告:$ API = @file_get_contents

+0

不,因爲'file_get_contents'不會引發異常。它會觸發一個'E_WARNING'。該異常由框架的錯誤/異常處理程序生成。 –

+1

抑制警告不是_handling it_ –

+1

然後,您將確實必須使用@來抑制警告,然後檢查$ api是否不爲假: if(!$ api === false) – Fonta