[英]How to handle GuzzleHttp errors
我从 API 获取数据,我想处理该 API 数据的错误,因为目前如果由于任何原因无法获取数据我的页面停止加载并显示错误,我想要的是如果因为任何原因获取 Z8A5DA52ED126447D359E70C0 结果失败了将值设置为 null,因此页面的 rest 可以仅加载此 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
任何想法?
根据:文档
您可以处理异常
GuzzleHttp\Exception\ClientException - 400 errors
GuzzleHttp\Exception\ServerException - 500 errors
或者你可以使用它的超级 class
GuzzleHttp\Exception\BadResponseException
您可以使用尝试捕获
$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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.