Skip to content
This repository was archived by the owner on Feb 10, 2025. It is now read-only.

Commit e10f278

Browse files
committed
catch jsondecode errors due to bad connections and handle them as twitter errors to allow retries
closes #410
1 parent 23d7da4 commit e10f278

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

twitter/api.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,12 @@ def _handle_response(self, req, uri, arg_data, _timeout=None):
389389
if len(data) == 0:
390390
return wrap_response({}, handle.headers)
391391
elif "json" == self.format:
392-
res = json.loads(data.decode('utf8'))
392+
try:
393+
res = json.loads(data.decode('utf8'))
394+
except json.decoder.JSONDecodeError as e:
395+
# it seems like the data received was incomplete
396+
# and we should catch it to allow retries
397+
raise TwitterError("Incomplete JSON data collected for %s (%s): %s)" % (uri, arg_data, e))
393398
return wrap_response(res, handle.headers)
394399
else:
395400
return wrap_response(
@@ -401,6 +406,7 @@ def _handle_response(self, req, uri, arg_data, _timeout=None):
401406
raise TwitterHTTPError(e, uri, self.format, arg_data)
402407

403408
def _handle_response_with_retry(self, req, uri, arg_data, _timeout=None):
409+
delay = 1
404410
retry = self.retry
405411
while retry:
406412
try:
@@ -423,6 +429,14 @@ def _handle_response_with_retry(self, req, uri, arg_data, _timeout=None):
423429
raise
424430
retry -= 1
425431
sleep(delay)
432+
except TwitterError as e:
433+
if isinstance(retry, int) and not isinstance(retry, bool):
434+
if retry <= 0:
435+
raise
436+
retry -= 1
437+
print("There was a problem dialoguing with the API; waiting for %ds..." % delay, file=sys.stderr)
438+
sleep(delay)
439+
delay *= 2
426440

427441

428442
class Twitter(TwitterCall):

0 commit comments

Comments
 (0)