Skip to content

Commit 6b12b14

Browse files
Merge pull request #47 from Shakti13-sys/main
Improve: Exception Handling Across Multiple Components
2 parents e57d69d + 5c6f7ee commit 6b12b14

File tree

4 files changed

+62
-4
lines changed

4 files changed

+62
-4
lines changed

components/chat_interface.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import streamlit.components.v1 as components
33
from datetime import datetime
44
from core.utils import get_current_time, get_ai_response, save_conversations
5+
import requests
56

67
# Inject JS to get user's local time zone
78
def set_user_time_in_session():
@@ -117,11 +118,25 @@ def format_memory(convo_history, max_turns=10):
117118
"time": get_current_time()
118119
})
119120

121+
except ValueError as e:
122+
st.error("I'm having trouble understanding your message. Could you please rephrase it?")
123+
active_convo["messages"].append({
124+
"sender": "bot",
125+
"message": "I'm having trouble understanding your message. Could you please rephrase it?",
126+
"time": get_current_time()
127+
})
128+
except requests.RequestException as e:
129+
st.error("Network connection issue. Please check your internet connection.")
130+
active_convo["messages"].append({
131+
"sender": "bot",
132+
"message": "I'm having trouble connecting to my services. Please check your internet connection and try again.",
133+
"time": get_current_time()
134+
})
120135
except Exception as e:
121-
st.error(f"An error occurred: {e}")
136+
st.error(f"An unexpected error occurred. Please try again.")
122137
active_convo["messages"].append({
123138
"sender": "bot",
124-
"message": "Im having trouble responding right now. Please try again in a moment.",
139+
"message": "I'm having trouble responding right now. Please try again in a moment.",
125140
"time": get_current_time()
126141
})
127142

components/emergency_page.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
from geopy.geocoders import Nominatim
33
import urllib.parse
44
from .sidebar import GLOBAL_RESOURCES
5+
import geopy.exc
6+
import requests
57

68

79
def render_emergency_page():
@@ -41,8 +43,20 @@ def render_emergency_page():
4143
st.error(
4244
f"Could not find a location for '{location_query}'. Please try again.")
4345
st.session_state.pop('location_info', None)
46+
except geopy.exc.GeocoderTimedOut:
47+
st.error("Location search timed out. Please try again with a more specific location.")
48+
st.session_state.pop('location_info', None)
49+
except geopy.exc.GeocoderUnavailable:
50+
st.error("Location service is currently unavailable. Please try again later.")
51+
st.session_state.pop('location_info', None)
52+
except geopy.exc.GeocoderQuotaExceeded:
53+
st.error("Location service quota exceeded. Please try again later.")
54+
st.session_state.pop('location_info', None)
55+
except requests.RequestException as e:
56+
st.error("Network error while searching for location. Please check your internet connection.")
57+
st.session_state.pop('location_info', None)
4458
except Exception as e:
45-
st.error(f"An error occurred during search: {e}")
59+
st.error(f"An unexpected error occurred during search. Please try again.")
4660
st.session_state.pop('location_info', None)
4761
else:
4862
st.warning("Please enter a location to search.")

core/config.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import streamlit as st
22
import google.generativeai as genai
33
from pathlib import Path
4+
import requests
45

56
# ---------- Logo and Page Config ----------
67
logo_path = str(Path(__file__).resolve().parent.parent / "TalkHealLogo.png")
@@ -77,8 +78,20 @@ def generate_response(user_input, model):
7778
{"role": "user", "parts": [user_input]}
7879
])
7980
return response.text
81+
except ValueError as e:
82+
st.error("❌ Invalid input or model configuration issue. Please check your input.")
83+
return None
84+
except google.generativeai.types.BlockedPromptException as e:
85+
st.error("❌ Content policy violation. Please rephrase your message.")
86+
return None
87+
except google.generativeai.types.GenerationException as e:
88+
st.error("❌ Failed to generate response. Please try again.")
89+
return None
90+
except requests.RequestException as e:
91+
st.error("❌ Network connection issue. Please check your internet connection.")
92+
return None
8093
except Exception as e:
81-
st.error(f"❌ Failed to generate response: {e}")
94+
st.error(f"❌ Unexpected error occurred: {e}")
8295
return None
8396

8497
# ---------- MAIN CHAT INTERFACE ----------

core/utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import json
55
import os
66
import requests
7+
import google.generativeai
78

89
def get_current_time():
910
"""Returns the user's local time formatted as HH:MM AM/PM."""
@@ -82,7 +83,22 @@ def get_ai_response(user_message, model):
8283
# Clean the response to remove any HTML or unwanted formatting
8384
cleaned_response = clean_ai_response(response.text)
8485
return cleaned_response
86+
except ValueError as e:
87+
# Handle invalid input or model configuration issues
88+
return "I'm having trouble understanding your message. Could you please rephrase it?"
89+
except google.generativeai.types.BlockedPromptException as e:
90+
# Handle content policy violations
91+
return "I understand you're going through something difficult. Let's focus on how you're feeling and what might help you feel better."
92+
except google.generativeai.types.GenerationException as e:
93+
# Handle generation errors
94+
return "I'm having trouble generating a response right now. Please try again in a moment."
95+
except requests.RequestException as e:
96+
# Handle network/API connection issues
97+
return "I'm having trouble connecting to my services. Please check your internet connection and try again."
8598
except Exception as e:
99+
# Log unexpected errors for debugging (you can add logging here)
100+
# import logging
101+
# logging.error(f"Unexpected error in get_ai_response: {e}")
86102
return "I'm here to listen and support you. Sometimes I have trouble connecting, but I want you to know that your feelings are valid and you're not alone. Would you like to share more about what you're experiencing?"
87103

88104
def cached_user_ip():

0 commit comments

Comments
 (0)