0

im creating a service, and in this service im getting some data from a api, it works fine, but now i need to handle some http requests, one of them is the 404, since sometimes the data im trying to retrieve is not found.

My method from my Service is:

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);
    }

When there is not data, since im not handling errors, i get this error:

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

What is the best way to handle this type of error?

Marco Santos
  • 41
  • 1
  • 8
  • Possible duplicate of [file\_get\_contents() how to fix error "Failed to open stream", "No such file"](https://stackoverflow.com/questions/20562368/file-get-contents-how-to-fix-error-failed-to-open-stream-no-such-file) – Alex Tartan Jul 14 '17 at 15:48

2 Answers2

2

Create this function in the helper:

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

and check if get_http_response_code($this->url."schedules/".$date."/schedule.json?api_key=".$this->api_key) != 200 .

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
BastienCtr
  • 229
  • 1
  • 7
-1

Can't you simply use a try/catch block around the file_get_contents?

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

And you could also suppress the warning by putting an @ in front of the call to file_get_contents(): $api = @file_get_contents

Fonta
  • 13
  • 4
  • no, because `file_get_contents` doesn't throw exceptions. it triggers an `E_WARNING`. The exception is generated by the framework's error/exception handler. – Alex Tartan Jul 14 '17 at 15:50
  • 1
    Suppressing the warning is not _handling it_ – Alex Tartan Jul 14 '17 at 15:52
  • 1
    Then you would indeed have to suppress the warning using an @ and after that check if $api isn't false: if (!$api === false) – Fonta Jul 14 '17 at 15:53