'e' 到底是什么,e.code() 或 e.read() 有什么作用?

What exactly is 'e' and what does e.code() or e.read() do?

try:
    response = urllib2.urlopen(request)
except urllib2.URLError as e:
    response = json.loads(e.read())
    return error(e.code(),response['errors'][0]['message'])
response = json.loads(response.read())
if 'errors' in response:
    return error(response['ErrorCode'],response['Error'])

这是我正在使用的一段代码,你可以帮助我参考这段代码。

e是捕获到的异常,这里是urllib2.URLErrorclass或其子class的一个实例。代码期望该实例定义 e.read()e.code() 方法。

但是,它有一些错误。它实际上假设它正在捕获 urllib2.HTTPError exception, a subclass of URLError. The exception handler certainly will catch such exceptions, but it could also be the base URLError, in which case there won't be an e.read() method! It also tries to call HTTPError.code,这不是方法而是属性。

HTTPError HTTP 错误代码会抛出异常,因此只有在服务器有响应时才会抛出。 e.read() 允许您从套接字读取响应主体,e.code 是服务器响应的 HTTP 代码。来自文档:

Though being an exception (a subclass of URLError), an HTTPError can also function as a non-exceptional file-like return value (the same thing that urlopen() returns). This is useful when handling exotic HTTP errors, such as requests for authentication.

要使代码在所有情况下都能正常工作,必须将其更正为:

try:
    response = urllib2.urlopen(request)
except urllib2.HTTPError as e:
    response = json.loads(e.read())
    return error(e.code, response['errors'][0]['message'])

也许有一个额外的 except urllib2.URLError as e: 块来处理不涉及 HTTP 响应的错误。