Tornado custom error handler for Static file

2019-07-04 07:41发布

问题:

How can I show custom 404 error page for static files?

in my current application handler I have added last pattern as follows

[
    (r'/(favicon.ico)', tornado.web.StaticFileHandler, {"path": mypath}),
    (r'/foo',FooHandler),
    (r'/bar',BarHandler),
    (r'/(.*)',ErrorHandler),
]

and this is my error handler

class ErrorHandler(BaseHandler):

    def get(self,d):
        self.status_code = 404
        self.show404(d)

If I visit http://localhost/abc I am getting my custom 404 page

but if I try to get http://localhost/static/abc.js I'm getting the ugly error like below

line 2286, in validate_absolute_path
raise HTTPError(404)
HTTPError: HTTP 404: Not Found 

Is there any way to get this working? How can I show my custom error page for static files

回答1:

This is a bit tricky; you need to subclass StaticFileHandler and override its write_error method, then install that class with static_handler_class Application setting.