【问题标题】:Catch-All global exception handler in App Engine for PythonApp Engine for Python 中的 Catch-All 全局异常处理程序
【发布时间】:2011-05-16 20:09:38
【问题描述】:

是否可以使用 Python 在 Google App Engine 中创建包罗万象的全局异常处理程序?

基本上,我想捕获所有未捕获的异常并优雅地处理它,同时向我发送一封带有回溯的电子邮件。

目前,对于所有未捕获的错误,用户会看到一个堆栈跟踪,其中包含一个 sn-p 代码。这是不可取的。

【问题讨论】:

    标签: google-app-engine exception-handling catch-all


    【解决方案1】:

    是的,这是可能的。
    您可以使用ereporter 包来完成此操作,该包允许通过电子邮件从您的应用程序接收异常报告。

    Ereporter 会报告两种异常:

    • 使用logging.exception('Your handled exception') 记录的异常
    • 任何未捕获的异常

    为了捕获所有异常,我将创建一个自定义 BaseHandler 类来覆盖handle_exception() 方法;您的所有请求处理程序都应该继承自这个基类。
    也可以看看Custom Error Responses

    下面是 BaseHandler 类的一个简单示例:

    class BaseHandler(webapp.RequestHandler):
    
        def handle_exception(self, exception, debug_mode):
            if debug_mode:
                webapp.RequestHandler.handle_exception(self, exception, debug_mode)
            else:
                logging.exception(exception)
                self.error(500)
                self.response.out.write(template.render('templdir/error.html', {}))
    

    【讨论】:

    • 太棒了!这似乎解决了我的一半问题,但是当启用此功能时,当发生未捕获的异常时用户会看到什么?是否有办法将用户重定向到所有未处理异常的默认错误页面?
    • 谢谢!我在 python 方面不是很好,能否请您包含一个关于如何为 webapp.RequestHandler 类执行此操作的代码 sn-p?真的很感激。
    • 太棒了!所以现在当我创建一个新类来处理让我们说“/” url时,我将不得不使用类 MainPage(BaseHandler) 而不是通常的类 MainPage(webapp.RequestHandler) ...我正确吗?
    • 非常感谢。这帮助很大。
    【解决方案2】:

    您可能希望通过在 BaseHandler 中调用以下内容来调用原始的 handle_exception:

    webapp.RequestHandler.handle_exception(self, exception, debug_mode)
    

    这里是上下文。

    from google.appengine.ext import webapp
    import sys
    import traceback
    
    class BaseHandler(webapp.RequestHandler):
        def handle_exception(self, exception, debug_mode):
            from main import emaildevs
            emaildevs('An error occurred on example.com', ''.join(traceback.format_exception(*sys.exc_info())))
            webapp.RequestHandler.handle_exception(self, exception, debug_mode)
    

    【讨论】:

      【解决方案3】:

      尝试: 称呼 除了: 发邮件

      http://docs.python.org/tutorial/errors.html

      【讨论】:

      • 我知道如何捕捉错误。我的问题是如何在 GAE 中运行的应用程序中全局捕获错误
      猜你喜欢
      • 1970-01-01
      • 2013-09-09
      • 2014-04-17
      • 2012-12-31
      • 2011-05-19
      • 2011-08-31
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多