raghavNCI commited on
Commit
37c8516
·
1 Parent(s): 24717ec

try except added

Browse files
Files changed (1) hide show
  1. routes.py +26 -15
routes.py CHANGED
@@ -15,21 +15,32 @@ def get_news_by_category(category: str, limit: int = 5):
15
  "max": limit,
16
  "token": GNEWS_API_KEY
17
  }
18
- response = requests.get(base_url, params=params)
19
- data = response.json()
20
-
21
- articles = []
22
- for article in data.get("articles", []):
23
- articles.append({
24
- "title": article["title"],
25
- "url": article["url"],
26
- "description": article.get("description"),
27
- "publishedAt": article["publishedAt"],
28
- "image": article.get("image"),
29
- "source": article["source"]["name"]
30
- })
31
-
32
- return articles
 
 
 
 
 
 
 
 
 
 
 
33
 
34
 
35
  @router.get("/")
 
15
  "max": limit,
16
  "token": GNEWS_API_KEY
17
  }
18
+
19
+ try:
20
+ response = requests.get(base_url, params=params, timeout=10)
21
+ response.raise_for_status() # raise exception for non-200 responses
22
+ data = response.json()
23
+
24
+ articles = []
25
+ for article in data.get("articles", []):
26
+ articles.append({
27
+ "title": article["title"],
28
+ "url": article["url"],
29
+ "description": article.get("description"),
30
+ "publishedAt": article["publishedAt"],
31
+ "image": article.get("image"),
32
+ "source": article["source"]["name"]
33
+ })
34
+
35
+ return articles
36
+
37
+ except requests.exceptions.RequestException as e:
38
+ print(f"[ERROR] Failed to fetch news: {e}")
39
+ return {"error": "Failed to fetch news from GNews API."}
40
+
41
+ except Exception as e:
42
+ print(f"[ERROR] Unexpected error: {e}")
43
+ return {"error": "An unexpected error occurred."}
44
 
45
 
46
  @router.get("/")