我们有一个Python 2项目,在那里我们积极地使用协同。我们找不到任何关于协同内异常处理的指导方针。
例如,龙卷风的这里首席开发人员提到了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只是扩展了基本异常类。此外,这里的讨论表明,在协同线内引发异常是合适的。
此外,活跃的“旋风”贡献者这里建议,增加异常是可以的:
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)在龙卷风协同中增加异常有什么坏处,还是我们应该raise gen.Return(exception_object)?
发布于 2017-05-12 16:33:35
在Python2中,只使用raise gen.Return(value)返回一个正常值,而不是引发异常。它与Python3中的coroutine中的return value完全相同。
要从协同线引发异常,正常的raise Exception()是正确的。coroutines的奇妙之处在于它们的异常处理语义与常规函数基本相同。
发布于 2017-05-12 23:12:03
在协同线中增加异常是完全正常的。当我说"coroutines不应该引发异常“时,我指的是在没有yield或await的情况下调用coroutine时所发生的情况:捕获异常并保持到coroutine的返回值为yielded或awaited为止。
https://stackoverflow.com/questions/43934107
复制相似问题