我有一個循環,逐行讀取文件並調用庫。但是,有時庫會使它擁有錯誤消息,然後我的整個循環停止工作,因爲它會終止循環。有沒有一種方法可以控制庫中的消息?如何在接收到此錯誤消息時繼續循環(即,如何檢查此錯誤消息是否存在以便我可以跳過它)?Python:錯誤庫後繼續
我得到的錯誤:
raise EchoNestAPIError(code, message, headers, http_status)
pyechonest.util.EchoNestAPIError: (u'Echo Nest API Error 5: The identifier specified does not exist [HTTP 200]',)
所以這是正在處理錯誤的庫中的部分代碼:
class EchoNestAPIError(EchoNestException):
"""
API Specific Errors.
"""
def __init__(self, code, message, headers, http_status):
if http_status:
http_status_message_part = ' [HTTP %d]' % http_status
else:
http_status_message_part = ''
self.http_status = http_status
formatted_message = ('Echo Nest API Error %d: %s%s' %
(code, message, http_status_message_part),)
super(EchoNestAPIError, self).__init__(code, formatted_message, headers)
class EchoNestIOError(EchoNestException):
"""
URL and HTTP errors.
"""
def __init__(self, code=None, error=None, headers=headers):
formatted_message = ('Echo Nest IOError: %s' % headers,)
super(EchoNestIOError, self).__init__(code, formatted_message, headers)
def get_successful_response(raw_json):
if hasattr(raw_json, 'headers'):
headers = raw_json.headers
else:
headers = {'Headers':'No Headers'}
if hasattr(raw_json, 'getcode'):
http_status = raw_json.getcode()
else:
http_status = None
raw_json = raw_json.read()
try:
response_dict = json.loads(raw_json)
status_dict = response_dict['response']['status']
code = int(status_dict['code'])
message = status_dict['message']
if (code != 0):
# do some cute exception handling
raise EchoNestAPIError(code, message, headers, http_status)
del response_dict['response']['status']
return response_dict
except ValueError:
logger.debug(traceback.format_exc())
raise EchoNestAPIError(-1, "Unknown error.", headers, http_status)
我試圖用一般的「除」沒有定義任何東西,並且適用於當我達到API限制時,但仍然不是因爲我提出這個問題的錯誤。這個錯誤似乎來自同一個班級。我不知道爲什麼它在限制錯誤上起作用,但不在另一方面。低於API限制的錯誤:
raise EchoNestAPIError(code, message, headers, http_status)
pyechonest.util.EchoNestAPIError: (u'Echo Nest API Error 3: 3|You are limited to 120 accesses every minute. You might be eligible for a rate limit increase, go to http://developer.echonest.com/account/upgrade [HTTP 429]',)
這是什麼錯誤處理 – therealprashant
閱讀[例外處理文檔](https://docs.python.org/2/tutorial/errors.html) – tdelaney