何时在GAE中使用try/except块

gae*_*fan 1 python google-app-engine exception-handling

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

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

  1. 防止用户看到异常
  2. 正确处理异常,这样他们就不会破坏我的应用程序

我应该在每次看到put和get的时候放一个try/except块吗?什么其他操作可能会失败,我应该用try/except包装?

Chr*_*loe 10

您可以创建一个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")
Run Code Online (Sandbox Code Playgroud)