0

I have data fetching from API and I want to handle errors for that API data because currently if for any reason that data couldn't be fetch my page stops loading and shows error, what I want is if getting api results failed for any reason just set value as null, therefore the rest of page can be loaded just this API data will not.

public function index() {
    $myData = ....;
    $minutes = 60;
    $forecast = Cache::remember('forecast', $minutes, function () {
        $app_id = env('HERE_APP_ID');
        $app_code = env('HERE_APP_CODE');
        $lat = env('HERE_LAT_DEFAULT');
        $lng = env('HERE_LNG_DEFAULT');
        $url = "https://weather.ls.hereapi.com/weather/1.0/report.json?product=forecast_hourly&name=Chicago&apiKey=$app_code&language=en-US";
        $client = new \GuzzleHttp\Client();
        $res = $client->get($url);
        if ($res->getStatusCode() == 200) {
            $j = $res->getBody();
            $obj = json_decode($j);
            $forecast = $obj->hourlyForecasts->forecastLocation;
        }
        return $forecast;
    });
    return view('panel.index', compact('myData', 'forecast'));
}

I want if forecast failed to fetch, data of $forecast be set to null

any idea?

1
  • there are a lot of answers regarding handling guzzle exception in stackoverflow as well as docs, you should search more for it Commented Jan 27, 2021 at 9:12

1 Answer 1

1

As per in the : Docs

You can handle the exception

GuzzleHttp\Exception\ClientException - 400 errors
GuzzleHttp\Exception\ServerException - 500 errors

or you can use the super class of it

GuzzleHttp\Exception\BadResponseException

You can use try catch

$client = new GuzzleHttp\Client;

try {

    $res = $client->get($url);

    if ($res->getStatusCode() == 200) {
        $j = $res->getBody();
        $obj = json_decode($j);
        $forecast = $obj->hourlyForecasts->forecastLocation;
    }

} catch (GuzzleHttp\Exception\BadResponseException $e) {
    // handle the response exception
    $forecast = null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.