Avital
Avital

Reputation: 81

Tornado custom error - there is better way?

In Tornado there is an option to override write_error function of request handler to create your custom error page.

In my application there are many Handlers, and i want to create custom error page when i get code 500. I thought to implement this by create Mixin class and all my handlers will inherit this mixing.

I would like to ask if there is better option to do it, maybe there is a way to configure application?

Upvotes: 3

Views: 1155

Answers (2)

André E Toscano
André E Toscano

Reputation: 31

I'm doing just like you mention. In order to do it you just have to create a class for each kind of error message and just override the write_error, like:

class BaseHandler(tornado.web.RequestHandler):

    def common_method(self, arg):
        pass


class SpecificErrorMessageHandler(tornado.web.RequestHandler):

    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            self.response(status_code,
                          'Resource not found. Check the URL.')
        elif status_code == 405:
            self.response(status_code, 
                          'Method not allowed in this resource.')
        else:
            self.response(status_code,
                          'Internal server error on specific module.')


class ResourceHandler(BaseHandler, SpecificErrorMessageHandler):

    def get(self):
        pass

The final class will inherit only the specified.

Upvotes: 3

J. Ghyllebert
J. Ghyllebert

Reputation: 2027

My workaround looks kinda similar as you're thinking of. I have a BaseHandler and all my handlers inherit this class.

class BaseHandler(tornado.web.RequestHandler):

    def write_error(self, status_code, **kwargs):
        """Do your thing"""

Upvotes: 7

Related Questions