From cf2cc32760f0ee2fcddc545f3719b062d993be2d Mon Sep 17 00:00:00 2001 From: Anas Ahmed <163267774+anasahhm@users.noreply.github.com> Date: Wed, 15 Oct 2025 16:36:37 +0530 Subject: [PATCH] Fix: handle missing carbonIntensity and fossilFuelPercentage safely MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The displayCarbonUsage function now includes null-safe checks to prevent runtime errors when CO₂ Signal API data is missing. Added user-facing fallback text and console warnings. --- 5-browser-extension/solution/src/index.js | 26 ++++++++++++----------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/5-browser-extension/solution/src/index.js b/5-browser-extension/solution/src/index.js index c8adb41e68..4a41ce6d63 100644 --- a/5-browser-extension/solution/src/index.js +++ b/5-browser-extension/solution/src/index.js @@ -35,37 +35,39 @@ const displayCarbonUsage = async (apiKey, region) => { try { await axios .get('https://api.co2signal.com/v1/latest', { - params: { - countryCode: region, - }, - headers: { - //please get your own token from CO2Signal https://www.co2signal.com/ - 'auth-token': apiKey, - }, + params: { countryCode: region }, + headers: { 'auth-token': apiKey }, }) .then((response) => { - let CO2 = Math.floor(response.data.data.carbonIntensity); + const data = response?.data?.data; + // ✅ Validate required data before using + if (data?.carbonIntensity == null || data?.fossilFuelPercentage == null) { + throw new Error('Missing carbon intensity or fossil fuel data'); + } + + let CO2 = Math.floor(data.carbonIntensity); calculateColor(CO2); loading.style.display = 'none'; form.style.display = 'none'; myregion.textContent = region; usage.textContent = - Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)'; + Math.round(data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)'; fossilfuel.textContent = - response.data.data.fossilFuelPercentage.toFixed(2) + + data.fossilFuelPercentage.toFixed(2) + '% (percentage of fossil fuels used to generate electricity)'; results.style.display = 'block'; }); } catch (error) { - console.log(error); + console.warn('Data fetch failed:', error.message); loading.style.display = 'none'; results.style.display = 'none'; - errors.textContent = 'Sorry, we have no data for the region you have requested.'; + errors.textContent = 'Sorry, data unavailable for the selected region.'; } }; + // set up api key and region const setUpUser = async (apiKey, region) => { localStorage.setItem('apiKey', apiKey);