Catch-All global exception handler in App Engine for Python

亡梦爱人 提交于 2019-11-30 07:14:44

问题


Is it possible to create a catch-all global exception handler in Google App Engine using Python?

Basically, I want to catch all un-caught exceptions and gracefully handle it, while sending an email with the traceback to me.

Currently, for all uncaught errors, the users see a stacktrace with a snippet of code in it. This is undesirable.


回答1:


Yes it is possible.
You can do it using the ereporter package that allows to receive exception reports from your application by email.

Ereporter will report two kind of exceptions:

  • exceptions logged with logging.exception('Your handled exception')
  • any uncaught exceptions

To catch all the exceptions, I would create a custom BaseHandler class overriding the handle_exception() method; all your request handlers should inherit from this Base class.
Have a look to Custom Error Responses too.

Here is a simple example of BaseHandler class:

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', {}))



回答2:


You might want to call the original handle_exception by calling the following in your BaseHandler:

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

Here it is in context.

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:


try: call except: sendemail

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



来源:https://stackoverflow.com/questions/4296504/catch-all-global-exception-handler-in-app-engine-for-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!