Catch-App Engine for Python中的所有全局异常处理程序

Der*_*ick 6 google-app-engine exception-handling catch-all

是否可以使用Python在Google App Engine中创建一个全能的全局异常处理程序?

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

目前,对于所有未捕获的错误,用户会看到包含一段代码的堆栈跟踪.这是不可取的.

sys*_*out 11

对的,这是可能的.
您可以使用做ereporter包,允许从电子邮件应用程序收到异常报告.

Ereporter将报告两种例外情况:

  • 记录的异常 logging.exception('Your handled exception')
  • 任何未被捕获的例外

为了捕获所有异常,我将创建一个覆盖handle_exception ()方法的自定义BaseHandler类; 您的所有请求处理程序都应该从此Base类继承.
看看自定义错误响应也是如此.

这是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', {}))
Run Code Online (Sandbox Code Playgroud)