From 7d2678422eb26f0930932fd8814c68eae0ea3dda Mon Sep 17 00:00:00 2001 From: Alejandro Sirgo Rica Date: Mon, 16 Dec 2024 11:40:34 +0100 Subject: cli: cleanup http error handling Use more specific exception request exception handling to provide better error messages. Define an interal request function for get, post and delete to reuse code. --- cli/cli.py | 59 ++++++++++++++++++++++++----------------------------------- 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/cli/cli.py b/cli/cli.py index 8dce3f5..0aaf885 100644 --- a/cli/cli.py +++ b/cli/cli.py @@ -46,53 +46,42 @@ def _log_http_status_code(res): class OgREST(): def __init__(self, ip, port, api_token): + if not ip or not port or not api_token: + raise ValueError("IP, port, and API token must be provided.") self.URL = f'http://{ip}:{port}' self.HEADERS = {'Authorization': api_token} - def get(self, path, payload=None): + def _request(self, method, path, payload, expected_status): try: - res = requests.get(f'{self.URL}{path}', - headers=self.HEADERS, - json=payload) - - if res.status_code != 200: + res = requests.request( + method, + f'{self.URL}{path}', + headers=self.HEADERS, + json=payload, + ) + if res.status_code not in expected_status: _log_http_status_code(res) return None - + return res + + except requests.exceptions.ConnectionError: + print("Cannot connect to ogserver") + except requests.exceptions.Timeout: + print("Request to ogserver timed out") + except requests.exceptions.TooManyRedirects: + print("Too many redirects occurred while contacting ogserver") except requests.exceptions.RequestException as e: - print(f"Error: Cannot connect to ogServer: {e}") - return None + print(f"An error occurred while contacting ogserver: {e}") + return None - return res + def get(self, path, payload, payload=None): + return self._request('GET', path, payload, expected_status={200}) def post(self, path, payload): - try: - res = requests.post(f'{self.URL}{path}', - headers=self.HEADERS, - json=payload) - - if res.status_code not in {200, 202}: - _log_http_status_code(res) - return None - - except requests.exceptions.RequestException as e: - print(f"Error: Cannot connect to ogServer: {e}") - return None - - return res + return self._request('POST', path, payload, expected_status={200, 202}) def delete(self, path, payload): - try: - res = requests.delete(f'{self.URL}{path}', - headers=self.HEADERS, - json=payload) - if res.status_code != 200: - _log_http_status_code(res) - return None - except IOError as e: - print(f"Error: Cannot connect to ogServer: {e}") - return None - return res + return self._request('DELETE', path, payload, expected_status={200}) class OgCLI(): -- cgit v1.2.3-18-g5258