【发布时间】:2017-05-12 09:27:27
【问题描述】:
我们有一个 Python 2 项目,我们在其中积极使用协程。我们找不到任何关于协程内部异常处理的指南。
例如,Tornado 的首席开发人员here 提到了coroutines should never raise an exception,但不清楚原因。看起来这种方法在 Tornado.web 本身中有效并大量使用:
https://github.com/tornadoweb/tornado/blob/master/demos/blog/blog.py#L180
class AuthCreateHandler(BaseHandler):
def get(self):
self.render("create_author.html")
@gen.coroutine
def post(self):
if self.any_author_exists():
raise tornado.web.HTTPError(400, "author already created")
hashed_password = yield executor.submit(
bcrypt.hashpw, tornado.escape.utf8(self.get_argument("password")),
bcrypt.gensalt())
tornado.web.HTTPError 只是扩展了基础 Exception 类。此外,https://github.com/tornadoweb/tornado/issues/759#issuecomment-91817197 此处的讨论表明在协程内引发异常是合适的。
另外here,活跃的 Tornado 贡献者建议引发异常是好的:
class PostHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self, slug):
post = yield db.posts.find_one({'slug': slug})
if not post:
raise tornado.web.HTTPError(404)
self.render('post.html', post=post)
在 Tornado 协程中引发异常是否有任何不利之处,或者我们应该 raise gen.Return(exception_object) 吗?
【问题讨论】: