public

Tornado Error Handling

I thought I'd keep posting my interesting tidbits about Tornado development and simple helpers here.  I found the need for some custom error messages, and along with everything

10 years ago

Latest Post Mastering Kubernetes: Key Metrics for Cluster Monitoring by Mike Moore public

I thought I'd keep posting my interesting tidbits about Tornado development and simple helpers here.  I found the need for some custom error messages, and along with everything else, really a need for a more robust base request handler... So I wrote one!  The premise is simple: Use this handler as your base class for ALL of your handlers and voila! Simple error handling.  This particular example only handles 404, but that's because it's an example.  Feel free to handle any and all codes you may choose with this:

# Simple Tornado base handler with error handling
class BaseHandler(tornado.web.RequestHandler):
    def __init__(self,application, request,**kwargs):
        super(BaseHandler,self).__init__(application,request)

    def write_error(self, status_code, **kwargs):
        if status_code == 404:
        self.render('errors/404.html',page=None)
        else:
            self.render('errors/unknown.html',page=None)

Take our fancy base handler and use it like so:

# Main Handler CRUD Example using the BaseHandler Class
class MainHandler(BaseHandler):
    # CREATE
    def put(self):
        pass

    # READ 
    def get(self):
        pass

    # UPDATE
    def post(self):
        pass

    # DELETE
    def delete(self):
        pass

Tada! And that's simple tornado error handling in 2 seconds!

Mike Moore

Published 10 years ago