2011-03-10 34 views
1

我最近开始使用GAE和Python开发我的第一个Web应用程序,这非常有趣。何时使用GAE中的try/except块

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

  1. 防止用户曾经看到异常
  2. 妥善处理例外,所以他们不会破坏我的应用程序

我应该把一个try/except块周围的每一个电话把和得到? 什么其他操作可能会失败,我应该试试/除外?

+0

可能重复[包罗万象的App Engine中的Python全局异常处理(http://stackoverflow.com/questions/4296504/catch-all-global-exception-handler-in-app-engine-for-python) – systempuntoout 2011-03-10 20:18:26

回答

10

您可以创建一个名为您的要求处理handle_exception应对非预期的情况下,方法。

当它击中了问题的Web应用程序框架将自动调用这个

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") 
+0

更好的解决方案:/ – Dimitry 2011-03-10 16:07:56

+0

这是(1)的一个很好的解决方案。对于(2),我想我需要确保任何失败都不会让我的应用处于不一致的状态。 – 2011-03-10 17:03:11

+0

是的,这是你的“最后一招”。如果您正在进行大量数据存储写入,并且存在可能会导致数据不一致的情况,请使用[transactions](http://code.google.com/appengine/docs/python/datastore/transactions.html)。但是尝试将事务保存在appengine中,因为如果您不完全了解数据存储,它们可能会导致问题。 – 2011-03-10 17:10:58

1

您可以将视图封装在能够捕获所有异常的方法中,记录它们并返回一个英俊的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 
+0

如果你设置响应状态为500,那么这个任务将被一次又一次地重试。所以,如果你的代码有问题,那么你将会耗尽你的配额。 – Sam 2011-03-14 02:26:06