Php 处理未找到的Http请求
我正在创建一个服务,在这个服务中,我从一个api获取一些数据,它工作得很好,但是现在我需要处理一些http请求,其中一个是404,因为有时候我试图检索的数据找不到 我的服务方法是:Php 处理未找到的Http请求,php,exception-handling,Php,Exception Handling,我正在创建一个服务,在这个服务中,我从一个api获取一些数据,它工作得很好,但是现在我需要处理一些http请求,其中一个是404,因为有时候我试图检索的数据找不到 我的服务方法是: public function getAllGamesFromDate($date = "2017-08-09", $tournament = "123") { $api = file_get_contents($this->url."schedules/".$date."/sched
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
处理此类错误的最佳方法是什么?您不能简单地在文件内容周围使用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在帮助程序中创建此函数来抑制警告:
function get_http_response_code($url) {
$headers = get_headers($url);
return substr($headers[0], 9, 3);
}
并检查是否
获取http\u响应\u代码($this->url.“schedules/”$date./schedule.json?api\u key=“.this->api\u key)
!=200
可能重复no,因为file\u get\u contents
不会引发异常。它会触发E_警告
。异常是由框架的错误/异常处理程序生成的。抑制警告不会处理它。此时,您确实必须使用@抑制警告,然后检查$api是否为false:if(!$api==false)