Handle bad http requests in api clients

Previously unhandled, the http requests should either fail hard, or
errors should be logged with details of the failed request.
This commit is contained in:
jo 2021-08-01 14:14:36 +02:00
parent d58fe19ae3
commit a6e9f3109c
1 changed files with 15 additions and 5 deletions

View File

@ -96,25 +96,35 @@ class ApiRequest:
self.logger.debug(final_url)
try:
if _post_data:
response = requests.post(
res = requests.post(
final_url,
data=_post_data,
auth=self.auth,
timeout=ApiRequest.API_HTTP_REQUEST_TIMEOUT,
)
else:
response = requests.get(
res = requests.get(
final_url,
params=params,
auth=self.auth,
timeout=ApiRequest.API_HTTP_REQUEST_TIMEOUT,
)
if "application/json" in response.headers["content-type"]:
return response.json()
return response
# Check for bad HTTP status code
res.raise_for_status()
if "application/json" in res.headers["content-type"]:
return res.json()
return res
except requests.exceptions.Timeout:
self.logger.error("HTTP request to %s timed out", final_url)
raise
except requests.exceptions.HTTPError:
self.logger.error(
f"HTTP request to '{res.request.url}' failed"
f" with status '{res.status_code}':\n{res.text}"
)
raise
def req(self, *args, **kwargs):
self.__req = lambda: self(*args, **kwargs)