【问题标题】:How to catch exception for which the name is not defined in context?如何捕获未在上下文中定义名称的异常?
【发布时间】:2013-07-23 13:50:42
【问题描述】:

我看到 python-requests library 崩溃并带有以下回溯:

Traceback (most recent call last):
  File "/usr/lib/python3.2/http/client.py", line 529, in _read_chunked
    chunk_left = int(line, 16)
ValueError: invalid literal for int() with base 16: b''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./app.py", line 507, in getUrlContents
    response = requests.get(url, headers=headers, auth=authCredentials, timeout=http_timeout_seconds)
  File "/home/dotancohen/code/lib/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/home/dotancohen/code/lib/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/home/dotancohen/code/lib/requests/sessions.py", line 338, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/dotancohen/code/lib/requests/sessions.py", line 441, in send
    r = adapter.send(request, **kwargs)
  File "/home/dotancohen/code/lib/requests/adapters.py", line 340, in send
    r.content
  File "/home/dotancohen/code/lib/requests/models.py", line 601, in content
    self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
  File "/home/dotancohen/code/lib/requests/models.py", line 542, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/home/dotancohen/code/lib/requests/packages/urllib3/response.py", line 222, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/home/dotancohen/code/lib/requests/packages/urllib3/response.py", line 173, in read
    data = self._fp.read(amt)
  File "/usr/lib/python3.2/http/client.py", line 489, in read
    return self._read_chunked(amt)
  File "/usr/lib/python3.2/http/client.py", line 534, in _read_chunked
    raise IncompleteRead(b''.join(value))
http.client.IncompleteRead: IncompleteRead(0 bytes read)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.2/threading.py", line 740, in _bootstrap_inner
    self.run()
  File "./app.py", line 298, in run
    self.target(*self.args)
  File "./app.py", line 400, in provider_query
    url_contents = getUrlContents(str(providerUrl), '', authCredentials)
  File "./app.py", line 523, in getUrlContents
    except http.client.IncompleteRead as error:
NameError: global name 'http' is not defined

可以看出,我试图捕捉requestsexcept http.client.IncompleteRead as error: 行引发的http.client.IncompleteRead: IncompleteRead(0 bytes read) 错误。但是,由于未定义 http,因此会抛出 NameError那么我怎样才能捕捉到这个异常呢?

这是引发异常的代码:

import requests
from requests_oauthlib import OAuth1

authCredentials = OAuth1('x', 'x', 'x', 'x')
response = requests.get(url, auth=authCredentials, timeout=20)

请注意,我不包括 http 库,尽管 requests 包括它。该错误非常间歇性(可能每隔几个小时发生一次,即使我每十秒运行一次requests.get() 命令)所以我不确定将http 库添加到导入是否有帮助。

无论如何,在一般意义上,如果包含库A又包含库B,那么不包含B自己就不可能从B捕获异常吗?

【问题讨论】:

标签: python exception-handling python-requests


【解决方案1】:

回答你的问题

无论如何,一般意义上,如果包含库A又包含库B,那么不包含B自己就不可能从B捕获异常吗?

是的。例如:

a.py:

import b

# do some stuff with b

c.py:

import a

# but you want to use b
a.b  # gives you full access to module b which was imported by a

虽然这可以完成工作,但它看起来并不那么漂亮,尤其是在现实世界中具有长的包/模块/类/函数名称。

因此,在您处理http 异常的情况下,请尝试找出requests 中的哪个包/模块导入http,以便您执行raise requests.XX.http.WhateverError,或者只是将其导入为http是一个标准库。

【讨论】:

【解决方案2】:

如果你不提供来源而只是粗壮,很难分析问题, 但请查看此链接:http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions

基本上, 尝试在代码中出现错误的任何地方捕获异常。 例外:

In the event of a network problem (e.g. DNS failure, refused connection, etc), 
Requests will raise a **ConnectionError** exception.

In the event of the rare invalid HTTP response, 
Requests will raise an **HTTPError** exception.

If a request times out, a **Timeout** exception is raised.

If a request exceeds the configured number of maximum redirections,
 a **TooManyRedirects** exception is raised.

All exceptions that Requests explicitly raises inherit 
from **requests.exceptions.RequestException.**

希望有所帮助。

【讨论】:

    猜你喜欢
    • 2021-07-05
    • 2013-08-13
    • 2017-05-24
    • 2012-12-07
    • 2012-07-20
    • 2021-10-02
    • 2019-07-07
    • 1970-01-01
    • 2017-05-20
    相关资源
    最近更新 更多