【发布时间】:2013-03-13 06:40:03
【问题描述】:
我在生产环境中使用 Google Appengine,目前我们的网站和控制台都出现 500 个错误。我们能做些什么来防止这些或更优雅地处理它们吗?
编辑:我们将 python 与 Webapp 一起使用
【问题讨论】:
-
您使用哪种语言? Python 与 web 应用程序?
我在生产环境中使用 Google Appengine,目前我们的网站和控制台都出现 500 个错误。我们能做些什么来防止这些或更优雅地处理它们吗?
编辑:我们将 python 与 Webapp 一起使用
【问题讨论】:
设置错误处理程序:http://code.google.com/appengine/docs/python/config/appconfig.html#Custom_Error_Responses
当应用程序中发生错误时,错误处理程序将无能为力。一种解决方案是包装应用程序以处理未捕获的异常:
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
def error_handler_middleware(app):
"""Wraps the application to catch uncaught exceptions."""
def wsgi_app(environ, start_response):
try:
return app(environ, start_response)
except Exception, e:
logging.exception(e)
# ... display a custom error message ...
response = webapp.Response()
response.set_status(500)
response.out.write('Ooops! An error occurred...')
response.wsgi_write(start_response)
return ['']
return wsgi_app
app = webapp.WSGIApplication([...])
app = error_handler_middleware(app)
def main():
util.run_wsgi_app(app)
if __name__ == '__main__':
main()
如果可以的话,试试webapp2。您可以将简单的函数设置为handle app-wide exceptions。
【讨论】:
handle_exception 并返回 500。覆盖 handle_exception - 或者更好,只是 error,handle_exception调用 - 在基处理程序类中是更好的选择。
.handle_exception()。仍然值得注意的是,webapp 只会捕获请求方法上发生的错误(多数);它不会捕获 404、错误的路线定义以及发生在 __init__ 和 initialize 上的那些。