Chris J. Vargo
Chris J. Vargo

Reputation: 2436

Error Handing HTTPError

Hi All I have the following error I want to handle (this happens from time to time when the wifi drops packets):

Traceback (most recent call last):
File "twittersearch.py", line 40, in <module>
data = json.load(urllib2.urlopen(response))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 503: Service Unavailable

The following:

while True:
    try:
        #iteration here
    except HTTPError:
        continue
    break

Doesn't handle the error. Any ideas on how to get it to retry the iteration when this error is thrown?

Upvotes: 0

Views: 398

Answers (1)

Roger Fan
Roger Fan

Reputation: 5045

Continue doesn't restart the loop, it simply moves on to the next loop. So this isn't simple to troubleshoot without knowing what is happening in the iteration.

You could try to move whatever increment step there is in that iteration after the try-except block, so that it isn't executed when an exception is thrown and the continue will therefore attempt to do the same thing.

i = 0
while i < 5:
    try:
        something(i)  # This sometimes throws an exception
    except MyError:
        continue

    i += 1  # This increment doesn't happen unless no exception is raised

If you're iterating over a list or something similar you could iterate over the indices and use the same logic, or write a function that will repeat a task until it succeeds with each element.

def myfunc(el):
    try:
        do_something(el)
    except MyError:
        myfunc(el)  # Retry the function if the exception is raised

mylist = ...  # List of things
for el in mylist:
    myfunc(el)

Upvotes: 1

Related Questions