2017-07-14 135 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