处理HTTP错误时出错

时间:2014-08-21 02:10:24

标签: python python-2.7

大家好我有以下我想要处理的错误(这种情况会在wifi丢包时不时发生):

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

以下内容:

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

不处理错误。有关如何在抛出此错误时重试迭代的任何想法?

1 个答案:

答案 0 :(得分:1)

继续不重启循环,它只是移动到下一个循环。因此,在不知道迭代中发生了什么的情况下进行故障排除并不容易。

您可以尝试在try-except块之后移动该迭代中的任何增量步骤,以便在抛出异常时不会执行它,因此continue将尝试执行相同的操作

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

如果你在列表或类似的东西上进行迭代,你可以迭代索引并使用相同的逻辑,或编写一个重复任务的函数,直到它成功完成每个元素。

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)