在我的程序中,我正在向一些主机做一些请求。问题是我无法正确捕获主机断开连接时引发的异常。我正在使用 tornado ,请求是异步的。 考虑以下代码:
self.http_client = AsyncHTTPClient()
try:
responses = yield [self.http_client.fetch(theUrl) for theUrl in URLS]
except Exception as e:
if (e[0] == 111) or (e[0] == 599):
#Do something
当主机断开连接时,我有时能够捕获异常,但仍然会被抛出。我得到例如打印到我的日志文件的错误消息:
ERROR:tornado.application:Multiple exceptions in yield list
Traceback (most recent call last):
File "/opt/felix-web-mon/env/lib/python2.7/site-packages/tornado/gen.py", line 828, in callback
result_list.append(f.result())
File "/opt/felix-web-mon/env/lib/python2.7/site-packages/tornado/concurrent.py", line 238, in result
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
error: [Errno 111] Connection refused
尽管我正在处理&#39; 111&#39;我的代码中的异常,它仍然被抛出。我怀疑这是因为我正在使用列表理解(我需要)。 我怎样才能抓住这个&#39; 收益列表中的多个例外&#39;在一个除了块?你能帮帮我吗?
答案 0 :(得分:1)
等待多个期货,通过简单地产生一个清单,将&#34;丢弃&#34;任何错误的所有回复。您可以使用:
yield
- 这个的好处是你得到的结果。你没有等到所有raise_error=False
请求完成(特别是最慢的请求)。fetch
中传递from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient
@coroutine
def main():
URLS = [
'http://amazon.com',
'https://www.kernel.org/some404',
'http://localhost:8787', # connection refused
'http://google.com'
]
http_client = AsyncHTTPClient()
responses = yield [http_client.fetch(theUrl, raise_error=False) for theUrl in URLS]
for idx, r in enumerate(responses):
print(URLS[idx])
if 200 <= r.code <= 299:
print('> ok')
elif 300 <= r.code <= 399:
print('> ok - redirect')
elif 400 <= r.code <= 499:
print('> client err: %s' % r.code)
elif 500 <= r.code <= 598:
print('> server err: %s' % r.code)
elif r.code == 599:
print('> 599 connection error or timedouted request')
# or something like below
#try:
# res = r.rethorw()
#except Exception:
# do something
IOLoop.instance().run_sync(main)
以取消提升看看Exception handling for parallel fetch requests,两者都有描述。
fatal: [vogo-alpha.cloudapp.net]: UNREACHABLE! => {"changed": false, "msg": "Authentication failure.", "unreachable": true}