Tornado中的`send_error`, `write_error`和`raise HTTPError`有什么区别?

RT,官方文档看的不是很懂:

RequestHandler.send_error(status_code=500, kwargs)**

Sends the given HTTP error code to the browser.

If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.

Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.


RequestHandler.write_error(status_code, kwargs)**

Override to implement custom error pages.

write_error may call write, render, set_header, etc to produce output as usual.

If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.

我理解的是send_error调用了write_error,所以写自定义错误页面的时候要自己实现write_error方法,抛出错误的时候使用send_error。那么又该在什么时候使用rasie tornado.web.HTTPError呢?

阅读 5k
2 个回答

HTTPError一般是用tornado访问某个url,然后这个url不存在,或者返回一个错误码的时候用到的。

from tornado.httpclient import HTTPClient, HTTPError
http_client = HTTPClient()
try:
    response = http_client.fetch(url, method='GET', request_timeout=120)
except HTTPError as http_error:
    print http_error
except Exception as e:
    print e
finally:
    http_client.close()

send_error是Torando发送错误状态码到浏览器,而write_error是对自定义的错误页面进行重写,是2个不同的操作。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题