This post discusses implementing custom error handling in the Tornado web framework by creating a reusable base handler class.

The Problem

I identified a need for custom error messages and a more robust foundation for request handlers across my Tornado application.

The Solution

The approach involves creating a base handler class that all application handlers inherit from. The key implementation uses the write_error method to intercept HTTP errors:

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)

Implementation

Handlers then inherit from this base class:

class MainHandler(BaseHandler):
    def put(self):
        pass
    def get(self):
        pass
    def post(self):
        pass
    def delete(self):
        pass

This pattern enables centralized error handling for all CRUD operations across the application.