在GAE中何时使用try/except块
我最近开始用GAE和Python开发我的第一个网页应用,感觉非常有趣。
不过我遇到一个问题,就是有些错误在我意想不到的时候出现(因为我对网页应用还不太熟悉)。我希望能做到:
- 让用户永远看不到错误信息
- 妥善处理这些错误,确保我的应用不会崩溃
我是不是应该在每次调用put和get的时候都加上try/except块?还有哪些操作可能会出错,我也应该用try/except来处理呢?
2 个回答
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
10
你可以在你的请求处理器上创建一个叫做 handle_exception
的方法,用来处理一些意外情况。
当遇到问题时,网络应用框架会自动调用这个方法。
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")