This article mainly introduces how tornado can capture and handle 404 errors. The method is simple. You only need to override the write_error method, the code below shows the errors in the path request listed in handlers.
If only one rule (r "/hello", HelloHandler) is defined, only requests with undefined paths such as/hello/other can be captured, the default 404 error page of Tornado is displayed directly, such as/he,/helloworld, And/he/other, without displaying custom error pages.
The solution is simple. You only need to add one (r ". * ", BaseHandler) is used to capture all requests not captured by other rules, overwrite the get method, and call the custom write_error method in the method. Example:
The Code is as follows:
Class BaseHandler (tornado. web. RequestHandler ):
Def get (self ):
Self. write_error (404)
Def write_error (self, status_code, ** kwargs ):
If status_code = 404:
Self. render ('Public/404.html ')
Elif status_code = 500:
Self. render ('Public/500.html ')
Else:
Self. write ('error: '+ str (status_code ))