如何处理 GuzzleHttp 错误

How to handle GuzzleHttp errors

我从 API 获取数据,我想处理 API 数据的错误,因为目前如果由于任何原因无法获取数据,我的页面将停止加载并显示错误,我想要的是,如果由于任何原因导致 api 结果失败,只需将值设置为 null,因此页面的其余部分可以加载,只是这个 API 数据不会。

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

我想如果预测获取失败,$forecast的数据设置为null

有什么想法吗?

根据:Docs

您可以处理异常

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

或者你可以使用它的超级class

GuzzleHttp\Exception\BadResponseException

你可以使用 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;
}