From a9f254bdfe5227bc5c475987386344c4539246b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gergely=20Nov=C3=A1k?= Date: Tue, 9 Jan 2024 08:54:05 +0100 Subject: [PATCH] Allow error messages without code field (#738) --- alpaca_trade_api/rest.py | 18 +++++++++++------- requirements/requirements_test.txt | 2 +- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/alpaca_trade_api/rest.py b/alpaca_trade_api/rest.py index db010328..0925502a 100644 --- a/alpaca_trade_api/rest.py +++ b/alpaca_trade_api/rest.py @@ -56,7 +56,7 @@ def __init__(self, error, http_error=None): @property def code(self): - return self._error['code'] + return self._error.get('code', self.status_code) @property def status_code(self): @@ -74,6 +74,15 @@ def response(self): if self._http_error is not None: return self._http_error.response +def raise_api_error(resp: requests.Response, http_error: requests.HTTPError): + try: + error = resp.json() + except: + raise http_error from None + if 'message' in error: + raise APIError(error, http_error) from None + raise http_error from None + class TimeFrameUnit(Enum): Minute = "Min" @@ -236,12 +245,7 @@ def _one_request(self, method: str, url: URL, opts: dict, retry: int): # retry if we hit Rate Limit if resp.status_code in retry_codes and retry > 0: raise RetryException() - if 'code' in resp.text: - error = resp.json() - if 'code' in error: - raise APIError(error, http_error) - else: - raise + raise_api_error(resp, http_error) if resp.text != '': return resp.json() return None diff --git a/requirements/requirements_test.txt b/requirements/requirements_test.txt index 87bb752a..055a4b1d 100644 --- a/requirements/requirements_test.txt +++ b/requirements/requirements_test.txt @@ -4,4 +4,4 @@ requests-mock coverage>=4.4.1 mock>=1.0.1 flake8 -deprecated \ No newline at end of file +deprecated