【问题标题】:when to use try/except blocks in GAE何时在 GAE 中使用 try/except 块
【发布时间】:2011-03-10 15:50:31
【问题描述】:

我最近开始使用 GAE 和 Python 开发我的第一个网络应用程序,这很有趣。

我遇到的一个问题是在我不期望它们时引发了异常(因为我是网络应用程序的新手)。我想:

  1. 防止用户看到异常
  2. 正确处理异常,以免它们破坏我的应用程序

我应该在每个 put 和 get 调用周围放置一个 try/except 块吗? 我应该用 try/except 包装哪些其他操作可能会失败?

【问题讨论】:

标签: python google-app-engine exception-handling


【解决方案1】:

您可以在请求处理程序上创建一个名为 handle_exception 的方法来处理意外情况。

webapp 框架会在遇到问题时自动调用它

class YourHandler(webapp.RequestHandler):

    def handle_exception(self, exception, mode):
        # run the default exception handling
        webapp.RequestHandler.handle_exception(self,exception, mode)
        # note the error in the log
        logging.error("Something bad happend: %s" % str(exception))
        # tell your users a friendly message
        self.response.out.write("Sorry lovely users, something went wrong")

【讨论】:

  • 这是 (1) 的绝佳解决方案。对于(2),我想我需要确保任何失败都不会使我的应用程序处于不一致的状态。
  • 是的,这是您的“最后手段”。如果您进行大量数据存储写入,并且在某些情况下可能会留下不一致的数据,请使用transactions。但请尽量在 appengine 中将事务保持在最低限度,因为如果您不完全了解数据存储区,它们可能会导致问题。
  • 很好的答案,尽管您为handle_exception 显示的实现与默认实现非常相似。相反,您可以覆盖self.error() 以输出有用的错误页面; handle_exception 打电话给self.error(500)。
【解决方案2】:

您可以将视图包装在一个方法中,该方法将捕获所有异常、记录它们并返回漂亮的 500 错误页面。

def prevent_error_display(fn):
    """Returns either the original request or 500 error page"""
    def wrap(self, *args, **kwargs):
        try:
            return fn(self, *args, **kwargs)
        except Exception, e:
            # ... log ...
            self.response.set_status(500)
            self.response.out.write('Something bad happened back here!')
    wrap.__doc__ = fn.__doc__
    return wrap


# A sample request handler
class PageHandler(webapp.RequestHandler): 
    @prevent_error_display
    def get(self):
        # process your page request

【讨论】:

  • 如果将响应状态设置为 500,则任务将一次又一次地重试。因此,如果您的代码有问题,那么您将耗尽您的配额。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 2019-07-14
相关资源
最近更新 更多