From de1504494d3b645b838b925f1c5873f1dfb0259d Mon Sep 17 00:00:00 2001 From: Muskankr Date: Mon, 13 Jul 2026 11:24:29 +0530 Subject: [PATCH] Add distinct error messages for city not found vs API/network failures --- Frontend/script.js | 15 +++++++++++++++ backend/alertsystem.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/Frontend/script.js b/Frontend/script.js index 1c044ca..1218142 100644 --- a/Frontend/script.js +++ b/Frontend/script.js @@ -263,3 +263,18 @@ if (scrollTopBtn) { }); }); } + +try { + const response = await fetch(`/weather?city=${city}&state=${state}&country=${country}`); + const data = await response.json(); + + if (!response.ok) { + document.getElementById("formErrors").textContent = data.error; + return; + } + + // Show weather data if successful + console.log(data); +} catch (err) { + document.getElementById("formErrors").textContent = "Unexpected error. Please try again."; +} diff --git a/backend/alertsystem.py b/backend/alertsystem.py index bde3472..e668759 100644 --- a/backend/alertsystem.py +++ b/backend/alertsystem.py @@ -2,6 +2,8 @@ import sys import requests +from flask import request, jsonify +from backend import app from dotenv import load_dotenv load_dotenv() @@ -697,6 +699,37 @@ def chatbot(): "Chatbot unavailable." }) + + +OPENWEATHER_API_KEY = "YOUR_KEY" + +@app.route("/weather") +def weather(): + city = request.args.get("city") + state = request.args.get("state") + country = request.args.get("country") + + if not city or not country: + return jsonify({"error": "Missing required fields"}), 400 + + try: + url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{state},{country}&appid={OPENWEATHER_API_KEY}" + resp = requests.get(url, timeout=5) + + # Handle API response codes + if resp.status_code == 404: + return jsonify({"error": "City not found. Please check spelling."}), 404 + elif resp.status_code != 200: + return jsonify({"error": "Weather service error. Try again later."}), resp.status_code + + data = resp.json() + return jsonify(data) + + except requests.exceptions.Timeout: + return jsonify({"error": "Weather service timed out. Please retry."}), 504 + except requests.exceptions.RequestException: + return jsonify({"error": "Network failure. Please check your connection."}), 503 + # ========================================================= # LOCAL RUN # =========================================================