我最近开始使用 GAE 和 Python 开发我的第一个 Web 应用程序,这很有趣。
我一直遇到的一个问题是在我不希望出现异常时出现异常(因为我是网络应用程序的新手)。我想:
- 防止用户看到异常
- 正确处理异常,以免它们破坏我的应用
我应该在每次调用 put 和 get 时都放置一个 try/except block 吗? 我应该用 try/except 包装哪些其他操作可能会失败?
请您参考如下方法:
您可以在请求处理程序上创建一个名为 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")
