Python请求异常处理Bad except子句顺序

时间:2015-11-18 19:53:47

标签: python exception-handling python-requests fault-tolerance

我正在使用请求库编写容错HTTP客户端,我想处理requests.exceptions

中定义的所有异常

以下是requests.exceptions

中定义的例外情况
'''
exceptions.BaseHTTPError         exceptions.HTTPError             exceptions.ProxyError            exceptions.TooManyRedirects
exceptions.ChunkedEncodingError  exceptions.InvalidSchema         exceptions.RequestException      exceptions.URLRequired
exceptions.ConnectionError       exceptions.InvalidURL            exceptions.SSLError              
exceptions.ContentDecodingError  exceptions.MissingSchema         exceptions.Timeout  
'''

当我在我的应用程序上使用pylint时,我收到一条错误消息,如http://pylint-messages.wikidot.com/messages:e0701中所述,表明订单不正确。我应该捕获错误的正确顺序是什么(以便通过首先捕获通用错误来掩盖更具体的错误),是否有通用的方法来确定错误?

2 个答案:

答案 0 :(得分:1)

大多数例外都是从RequestExceptionConnectionError(它本身继承自RequestException)继承的。 Python按照您在脚本中编写的顺序检查异常。如果您想单独捕获异常,请先放置叶子最多的异常,然后是ConnectionError,最后是RequestException。或者,只需抓住RequestException即可捕获所有这些内容。

答案 1 :(得分:0)

我写了一个处理requests.exception.RequestException

的装饰器
def handle_reqexcept(func):
    def handle(*args, **kw):
        try:
            return func(*args, **kw)
        except requests.exceptions.RequestException:
            return
    return handle

<小时/>

我写的实际功能是:

def handle_reqexcept(func):
    '''
    This decorator handles request.excptions
    '''
    @wraps(func)
    def handle(*args, **kw):
        '''
        Handle RequestException
        '''
        try:
            return func(*args, **kw)
        except requests.exceptions.RequestException as error:
            LOGGER.log_error(error)
    return handle
相关问题