Python:错误库后继续

标签 python loops

我有一个循环逐行读取文件并调用库。但是,有时该库会生成自己的错误消息,然后我的整个循环就会停止工作,因为它终止了循环。有没有办法可以控制库中的消息?当收到此错误消息时,如何使循环继续(即如何检查此错误消息是否存在以便我可以跳过它)?

我收到的错误:

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)

我尝试使用通用的“异常(exception)”而不定义任何内容,这适用于我达到 API 限制的情况,但仍然不适用于我提出这个问题的错误。这个错误似乎来自同一个类(class)。我不知道为什么它适用于限制错误,但不适用于其他错误。以下是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 block 内执行的每一行代码都可能会导致异常,然后在 except block 中“捕获”该异常(有一个额外的finally block ,更多内容请参见文档)。上面的示例只是抑制了异常,但这可能不是理想的解决方案。

异常是该语言的一个基本特性,您至少应该阅读 official docs开始吧。

关于Python:错误库后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311024/

相关文章:

javascript - CSS 使用循环使用 jquery

java - 一个循环,要求输入一定数量的数字并输出其中有多少个是偶数

python - 属性错误 : 'module' object has no attribute 'urls'

python - 如何在python中的特定索引处获取列表中没有元素的所有元素?

python - 使用 tkinter 中的链接打开一个新窗口

c - [GTK]将 g_signal_connect 中的循环计数器传递给 g_callback

c++ - 为什么 return 会改变我的值(value)?

javascript - 循环中的异步函数 - 使变量在内部函数中可用

python - SymPy,使用已知模式或子表达式的简化/替换

python - 在 Python 中测试数学表达式的等价性