From 36f2fddc8be6be02d3d404ebe5b6494c807553a5 Mon Sep 17 00:00:00 2001 From: Dale Davies Date: Thu, 31 Mar 2022 11:08:15 +0100 Subject: [PATCH] Improve handling of CURL errors in weatherdata API --- jumpapp/api/weatherdata.php | 6 ++++-- jumpapp/assets/js/src/classes/Weather.js | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/jumpapp/api/weatherdata.php b/jumpapp/api/weatherdata.php index d8d9a7e..97835bd 100644 --- a/jumpapp/api/weatherdata.php +++ b/jumpapp/api/weatherdata.php @@ -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; \ No newline at end of file diff --git a/jumpapp/assets/js/src/classes/Weather.js b/jumpapp/assets/js/src/classes/Weather.js index 48c2b3c..c588971 100644 --- a/jumpapp/assets/js/src/classes/Weather.js +++ b/jumpapp/assets/js/src/classes/Weather.js @@ -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';