Improve handling of CURL errors in weatherdata API

This commit is contained in:
Dale Davies
2022-03-31 11:08:15 +01:00
parent 9db70b6ea4
commit 36f2fddc8b
2 changed files with 10 additions and 3 deletions

View File

@@ -35,6 +35,9 @@ $url = $owmapiurlbase
.'&lon=' . $latlong[1]
.'&appid=' . $config->get('owmapikey', false);
// Output header here so we can return early with a json response if there is a curl error.
header('Content-Type: application/json; charset=utf-8');
// Use the cache to store/retrieve data, make an md5 hash of latlong so it is not possible
// to track location history form the stored cache.
$weatherdata = $cache->load(cachename: 'weatherdata', key: md5(json_encode($latlong)), callback: function() use ($url) {
@@ -53,11 +56,10 @@ $weatherdata = $cache->load(cachename: 'weatherdata', key: md5(json_encode($latl
curl_close($ch);
// If we had an error then return the error message and exit, otherwise return the API response.
if (isset($curlerror)) {
die($curlerror);
die(json_encode(['error' => $curlerror]));
}
return $response;
});
// We made it here so output the API response as json.
header('Content-Type: application/json; charset=utf-8');
echo $weatherdata;

View File

@@ -24,8 +24,13 @@ export default class Weather {
fetch(apiurl)
.then(response => response.json())
.then(data => {
if (data.error) {
console.error('JUMP ERROR: There was a problem contacting the OWM API');
return;
}
if (data.cod === 401) {
alert('The OWM API key is invalid, check config.php');
console.error('JUMP ERROR: The OWM API key is invalid, check config.php');
return;
}
// Determine if we should use the day or night variant of our weather icon.
var daynightvariant = 'night';