# Tornado Error Handling

> Implementing custom error handling in the Tornado web framework using a reusable base handler class.

- Canonical URL: https://webofmike.com/tornado-error-handling/
- Author: Mike Moore (https://webofmike.com/about/)
- Published: 2014-02-09
- Last modified: 2014-02-09
- Tags: Code, Tutorials
- Cite as: Mike Moore, "Tornado Error Handling", Web of Mike (webofmike.com), 2014-02-09. https://webofmike.com/tornado-error-handling/


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:

```python
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:

```python
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.

