6

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.

Lipis
  • 21,388
  • 20
  • 94
  • 121
Derick
  • 63
  • 1
  • 4

3 Answers3

11

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', {}))
systempuntoout
  • 71,966
  • 47
  • 171
  • 241
  • Awesome! This seems to solve half my problem, but when this is enabled what will the user see when an un-caught exception occurs? Is there someway to redirect the user to a default error page for all unhandled exceptions? – Derick Nov 28 '10 at 12:21
  • Thanks! I am not that great at python, could you please include a code snippet on how to do this for the webapp.RequestHandler class? Would really appreciate. – Derick Nov 28 '10 at 12:50
  • 1
    Awesome! So now when I will create a new class to handle lets say the "/" url, I will have to use class MainPage(BaseHandler) instead of the usual class MainPage(webapp.RequestHandler) ... am I correct? – Derick Nov 28 '10 at 14:19
1

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)
crizCraig
  • 8,487
  • 6
  • 54
  • 53
-4

try: call except: sendemail

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

  • I am aware how to catch errors. My question is how can I catch errors globally in my application running in GAE – Derick Nov 28 '10 at 11:48