Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

php - How to handle GuzzleHttp errors

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 GuzzleHttpClient();
        $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?

question from:https://stackoverflow.com/questions/65914894/how-to-handle-guzzlehttp-errors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As per in the : Docs

You can handle the exception

GuzzleHttpExceptionClientException - 400 errors
GuzzleHttpExceptionServerException - 500 errors

or you can use the super class of it

GuzzleHttpExceptionBadResponseException

You can use try catch

$client = new GuzzleHttpClient;

try {

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

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

} catch (GuzzleHttpExceptionBadResponseException $e) {
    // handle the response exception
    $forecast = null;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...