简体   繁体   中英

when to use try/except blocks in GAE

I've recently started developing my first web app with GAE and Python, and it is a lot of fun.

One problem I've been having is exceptions being raised when I don't expect them (since I'm new to web apps). I want to:

  1. Prevent users from ever seeing exceptions
  2. Properly handle exceptions so they don't break my app

Should I put a try/except block around every call to put and get? What other operations could fail that I should wrap with try/except?

You can create a method called handle_exception on your request handlers to deal with un-expected situations.

The webapp framework will call this automatically when it hits an issue

class YourHandler(webapp.RequestHandler):

    def handle_exception(self, exception, mode):
        # run the default exception handling
        webapp.RequestHandler.handle_exception(self,exception, mode)
        # note the error in the log
        logging.error("Something bad happend: %s" % str(exception))
        # tell your users a friendly message
        self.response.out.write("Sorry lovely users, something went wrong")

You can wrap your views in a method that will catch all exceptions, log them and return a handsome 500 error page.

def prevent_error_display(fn):
    """Returns either the original request or 500 error page"""
    def wrap(self, *args, **kwargs):
        try:
            return fn(self, *args, **kwargs)
        except Exception, e:
            # ... log ...
            self.response.set_status(500)
            self.response.out.write('Something bad happened back here!')
    wrap.__doc__ = fn.__doc__
    return wrap


# A sample request handler
class PageHandler(webapp.RequestHandler): 
    @prevent_error_display
    def get(self):
        # process your page request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM