bastianwenske/python-wekan

Better exception handling on the wekan client requests

C0rn3j opened this issue · 0 comments

Currently the code does not care if the server is 502 and throws a generic exception.

It would be nice if it returned a more specific exception in the case of a connection failure that I could handle, instead of a generic JSON decode error.

def fetch_json(self, uri_path, http_method="GET", payload=None):
"""
Make a request to the wekan api.
:return: Response body
:rtype: dict (json)
"""
url = self.base_url + uri_path
headers = {'Content-Type': 'application/json; charset=utf-8'}
if payload is None:
payload = {}
try:
if self.token_expire_date and self.__is_api_token_expired():
self.__renew_login_data()
headers['Authorization'] = f'Bearer {self.token}'
except AttributeError:
# pass if the variable self.token_expire_date isn't defined
pass
response = requests.request(method=http_method, url=url, headers=headers, data=json.dumps(payload))
try:
if response.status_code not in (200, 201):
if "Username already exists" in response.json()['reason']:
raise UsernameAlreadyExists
else:
raise Exception(f'Error while talking to API. Please see HTTP-Response: \n {response.text}')
except requests.exceptions.JSONDecodeError:
if response.status_code == 500 and http_method == "DELETE":
# There are errors when deleting some resources via api e.g.
# delete cards responds with "Internal Server Error" and
# status 500 even if the card has been deleted successfully
return response.text
else:
raise Exception(f'Could not decode the API response. Please see HTTP-Response: \n {response.text}')
return response.json()

Exception has occurred: Exception       (note: full exception trace is shown but execution is paused at: wekanLoop)
Could not decode the API response. Please see HTTP-Response: 
 <html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.24.0</center>
</body>
</html>
StopIteration: 0

During handling of the above exception, another exception occurred:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

  File "main.py", line 577, in wekan
    wekan = WekanClient(
            ^^^^^^^^^^^^
  File "main.py", line 703, in wekanLoop (Current frame)
    wekan()
Exception: Could not decode the API response. Please see HTTP-Response: 
 <html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.24.0</center>
</body>
</html>