【发布时间】:2015-05-18 19:05:33
【问题描述】:
我有一个循环,它逐行读取文件并调用库。但是,有时该库会生成自己的错误消息,然后我的整个循环停止工作,因为它终止了循环。有没有办法可以控制库中的消息?收到此错误消息时如何使循环继续(即,如何检查此错误消息是否存在以便我可以跳过它)?
我得到的错误:
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]',)
【问题讨论】:
-
这就是错误处理的目的