2011-03-10 33 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