![](/img/trans.png)
[英]How to continue the requests library function after receiving the error using python?
[英]Python: continue after error library
我有一个循环,逐行读取文件并调用库。 但是,有时该库使自己产生错误消息,然后我的整个循环停止工作,因为它终止了循环。 有什么方法可以控制库中的消息吗? 收到此错误消息时,如何使我的循环继续进行(即,如何检查此错误消息是否存在,以便可以跳过它)?
我得到的错误:
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]',)
您可以在try/except
-block中捕获异常。
例:
with open(your_file, "r") as f:
for line in f:
try:
api_call(line)
except pyechonest.util.EchoNestAPIError:
pass # or continue if you wish to skip processing this line.
try
在try
-block内部执行的每一行代码都可能导致异常,然后将其“捕获”在except
-block中(还有一个额外的finally
-block,在文档中有更多介绍)。 上面的示例只是抑制了该异常,但这可能不是理想的解决方案。
异常是该语言的基本功能,因此您至少应该阅读官方文档才能开始使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.