简体   繁体   中英

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?

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"""

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.

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