Skip to content

Commit

Permalink
fix: API Exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
ghadeer-x committed Mar 4, 2024
1 parent b6f7190 commit 198ce81
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,24 @@ with httpx.Client(base_url=base_path, verify=api_config.verify, timeout=api_conf
{% endif %}
{% endif %}
) as inital_response:
if inital_response.status != {{ return_type.status_code }}:
raise HTTPException(response=inital_response)

if inital_response.status != {{ return_type.status_code }}:
response = None
{% if async_client %}
try:
response = await inital_response.json()
except Exception as e:
response = await inital_response.text()
{% else %}
try:
response = inital_response.json()
except Exception as e:
response = inital_response.text
{% endif %}
{% if async_client %}
raise ApiException(status_code=inital_response.status, response=response)
{% else %}
raise ApiException(status_code=inital_response.status_code, response=response)
{% endif %}
{% if return_type.type is none or return_type.type.converted_type is none %}
return None
{% elif return_type.type is not none and return_type.type.converted_type == "str" and async_client %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,23 @@ class APIConfig(BaseModel):


class HTTPException(Exception):
def __init__(self, response : Optional[Response] = None, error: Optional[Any]=None):
def __init__(self, response : Optional[Response] = None, error: Optional[Any]=None, async_client:Optional[bool] = False):

try:

self.details = ErrorResponseDetails(**response.json().get("detail"))

if response.json().get("response", None):
self.details.response = response.json().get("response")
if async_client:
self.details = ErrorResponseDetails(**response.json().get("detail"))

if response.json().get("response", None):
self.details.response = response.json().get("response")
else:
self.details = ErrorResponseDetails(**response.get("detail"))

except Exception as e:
self.details = response.text

if hasattr(response, "text"):
self.details = response.text
else:
self.details = response

if response is not None:
if hasattr(response, "status_code"):
self.status_code = response.status_code
Expand Down

0 comments on commit 198ce81

Please sign in to comment.