首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Tornado中的异常处理

Python Tornado中的异常处理
EN

Stack Overflow用户
提问于 2011-09-26 06:42:31
回答 2查看 10.8K关注 0票数 5

我正在尝试这样处理AsyncClient.fetch中发生的异常:

代码语言:javascript
复制
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()

并查看下一个输出:

代码语言:javascript
复制
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

我做错了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-02 07:18:18

根据Tornado documentation的说法

如果在获取过程中发生错误,则提供给回调的错误具有一个非None HTTPResponse属性,该属性包含请求过程中遇到的异常。您可以调用response.rethrow()在回调中抛出异常(如果有)。

代码语言:javascript
复制
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()

您在控制台上看到的消息只是一个警告(通过logging.warning发送)。它是无害的,但如果它真的困扰您,请参阅logging模块了解如何过滤它。

票数 9
EN

Stack Overflow用户

发布于 2011-09-28 08:04:30

我根本不知道Tornado,但我看了一眼,你根本不能用这种方式捕捉异常。异常是在_HTTPConnection()的构造函数中生成的,并且该构造函数中的大多数代码已经被不同的堆栈上下文包装:

代码语言:javascript
复制
    with stack_context.StackContext(self.cleanup):
        parsed = urlparse.urlsplit(_unicode(self.request.url))
        [...]

因此,基本上无论何时在那里生成异常(在您的示例中是gaierror),它都已经被捕获并通过self.cleanup处理,这反过来又生成一个599响应AFAICT:

代码语言:javascript
复制
@contextlib.contextmanager
def cleanup(self):
    try:
        yield
    except Exception, e:
        logging.warning("uncaught exception", exc_info=True)
        self._run_callback(HTTPResponse(self.request, 599, error=e,
                            request_time=time.time() - self.start_time,
                            ))

不确定这是否回答了您的问题。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7549120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档