如何在Python中区分超时错误和其他URLError?

5 投票
2 回答
4285 浏览
提问于 2025-04-16 14:37

如何区分Python中的超时错误和其他URLError错误?

编辑

当我捕捉到一个URLError时,它可能是临时名称解析失败超时,或者其他一些错误?我该如何区分它们呢?

2 个回答

0

我用下面的代码来区分超时错误和其他的网络错误。

except URLError, e:
    if e.reason.message == 'timed out':
        # handle timed out exception
    else:
        # other URLError
5

我使用下面的选项2的代码……不过如果想要更全面的答案,可以看看Michael Foord的urllib2页面

如果你使用下面的选项1或选项2,你可以在except语句中根据e.codee.reason添加很多智能判断和分支逻辑。

选项1:

from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError, e:
    print 'The server couldn\'t fulfill the request.'
    print 'Error code: ', e.code
except URLError, e:
    print 'We failed to reach a server.'
    print 'Reason: ', e.reason
else:
    # everything is fine

选项2:

from urllib import urlencode
from urllib2 import Request
# insert other code here...
    error = False
    error_code = ""
    try:
        if method.upper()=="GET":
            response = urlopen(req)
        elif method.upper()=="POST":
            response = urlopen(req,data)
    except IOError, e:
        if hasattr(e, 'reason'):
            #print 'We failed to reach a server.'
            #print 'Reason: ', e.reason
            error = True
            error_code = e.reason
        elif hasattr(e, 'code'):
            #print 'The server couldn\'t fulfill the request.'
            #print 'Error code: ', e.code
            error = True
            error_code = e.code
    else:
        # info is dictionary of server parameters, such as 'content-type', etc...
        info = response.info().dict
        page = response.read()

撰写回答