From 9437b05caaee3725eeefae00533e4b7508175223 Mon Sep 17 00:00:00 2001 From: hamedsh Date: Sun, 19 May 2024 07:09:04 +0100 Subject: [PATCH] Improve error handling in ApiClient A more robust error handling strategy has been incorporated into the ApiClient, specifically in the request method. HTTP errors are now being caught and raised as ApiClientError exceptions, providing more specific and actionable error details. The commit also introduces minor code format changes for readability. --- mailchimp_transactional/api_client.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/mailchimp_transactional/api_client.py b/mailchimp_transactional/api_client.py index c319fac..4f838b4 100644 --- a/mailchimp_transactional/api_client.py +++ b/mailchimp_transactional/api_client.py @@ -15,11 +15,13 @@ import requests import json + class ApiClientError(Exception): def __init__(self, text, status_code): self.text = text self.status_code = status_code + class ApiClient(object): def __init__(self): self.host = "https://mandrillapp.com/api/1.0" @@ -61,19 +63,24 @@ def call_api(self, resource_path, method, header_params=None, body=None, **kwarg # perform request and return response res = self.request(method, url, body, headers) + try: + res.raise_for_status() + except requests.exceptions.HTTPError: + raise ApiClientError(text=res.text, status_code=res.status_code) + try: if 'application/json' in res.headers.get('content-type'): data = res.json() else: data = res.text - except Exception as err: + except Exception: data = None if data: if (res.ok): return data else: - raise ApiClientError(text = data, status_code = res.status_code) + raise ApiClientError(text=data, status_code=res.status_code) else: return res @@ -86,4 +93,4 @@ def request(self, method, url, body=None, headers=None, timeout=None): else: raise ValueError( "http method must be `POST`" - ) \ No newline at end of file + )