Python请求异常处理错误的except子句ord

2024-09-30 05:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用请求库编写一个容错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所述,它表明顺序不正确。我应该以什么样的顺序捕捉错误(这样就不会通过先捕捉一般错误来掩盖更具体的错误),有没有通用的方法来确定这一点?在


Tags: http客户机定义顺序错误requestsexceptionspylint
2条回答

大多数异常继承自RequestExceptionConnectionError(它本身继承自RequestException)。Python按照在脚本中编写异常的顺序检查异常。如果要单独捕获异常,请将大多数叶异常放在第一位,后跟ConnectionError,并以RequestException结尾。或者,只需捕获RequestException,它将捕获所有这些对象。在

我编写了一个decorator来处理requests.exception.RequestException

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


我写的实际函数是:

^{pr2}$

相关问题 更多 >

    热门问题