Myk*_*hko 5 python exception-handling tornado
我试图以AsyncClient.fetch这种方式处理异常:
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado.stack_context import ExceptionStackContext
from tornado import ioloop
def handle_exc(*args):
print('Exception occured')
return True
def handle_request(response):
print('Handle request')
http_client = AsyncHTTPClient()
with ExceptionStackContext(handle_exc):
http_client.fetch('http://some123site.com', handle_request)
ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)
并看到下一个输出:
WARNING:root:uncaught exception
Traceback (most recent call last):
File "/home/crchemist/python-3.2/lib/python3.2/site-packages/tornado-2.0-py3.2.egg/tornado/simple_httpclient.py", line 259, in cleanup
yield
File "/home/crchemist/python-3.2/lib/python3.2/site-packages/tornado-2.0-py3.2.egg/tornado/simple_httpclient.py", line 162, in __init__
0, 0)
socket.gaierror: [Errno -5] No address associated with hostname
Handle request
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
根据龙卷风文件:
如果在获取期间发生错误,则给予回调的HTTPResponse具有非None错误属性,该属性包含请求期间遇到的异常.您可以调用response.rethrow()以在回调中抛出异常(如果有).
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado.stack_context import ExceptionStackContext
from tornado import ioloop
import traceback
def handle_exc(*args):
print('Exception occured')
return True
def handle_request(response):
if response.error is not None:
with ExceptionStackContext(handle_exc):
response.rethrow()
else:
print('Handle request')
http_client = AsyncHTTPClient()
http_client.fetch('http://some123site.com', handle_request)
http_client.fetch('http://google.com', handle_request)
ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)
您在控制台上看到的消息只是一个警告(通过发送logging.warning).这是无害的,但如果它真的困扰你,请参阅日志模块以了解如何过滤它.