From b8a20e8511de5b8ebb48c07b8f524e36c383cebd Mon Sep 17 00:00:00 2001 From: Daan Koning Date: Tue, 22 Nov 2022 19:59:25 +0100 Subject: [PATCH] Improved error handling --- logic.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/logic.py b/logic.py index 3304bbc..6d24ed5 100644 --- a/logic.py +++ b/logic.py @@ -5,11 +5,29 @@ import requests BASE_URL = "https://api.the-odds-api.com/v4" +class AuthenticationException(RuntimeError): + pass + + +class RateLimitException(RuntimeError): + pass + + +def handle_faulty_response(response: requests.Response): + if response.status_code == 401: + raise AuthenticationException("Failed to authenticate with the API. is the API key valid?") + elif response.status_code == 429: + raise RateLimitException("Encountered API rate limit.") + + def get_sports(key: str) -> set[str]: url = f"{BASE_URL}/sports/" querystring = {"apiKey": key} response = requests.get(url, params=querystring) + if not response: + handle_faulty_response(response) + return {item["group"] for item in response.json()} @@ -23,6 +41,9 @@ def get_data(key: str, sport: str, region: str = "eu"): } response = requests.get(url, params=querystring) + if not response: + handle_faulty_response(response) + return response.json()