是否可以使用 Python 在 Google App Engine 中创建一个包罗万象的全局异常处理程序?
基本上,我想捕获所有未捕获的异常并优雅地处理它,同时向我发送一封包含回溯的电子邮件。
目前,对于所有 Uncaught Error ,用户会看到一个堆栈跟踪,其中包含一段代码。这是不可取的。
是的,这是可能的。
您可以使用 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', {}))
我是一名优秀的程序员,十分优秀!