Web development often calls for gracefully handling of non-existent pages or broken links that users request for. A simple way to achieve error handling in Tornado is with:
-
tornado.web.HTTPError - Exception handler that can used to generate error code of specified type. It is often used to raise an exception as we would see in the example below
-
send_error - Generates an error page of the status code provided along with error description if debug=True
In the example below, when user generates a GET request on http://127.0.0.1:8888/articles/, articles along with author names are shown up.
But when GET request is made on http://127.0.0.1:8888/articles/1, since there is no Id implementation for articles page, error is handled with self.send_error(500) or raise tornado.web.HTTPError(404, ‘Page Not Found Error!!’)
Case1: raise tornado.web.HTTPError(404, ‘Page Not Found Error!!’) is enabled
- Traceback (most recent call last): —– Traceback is noticed on web page
File “/home/ubuntu/tornado-2.2/tornado/web.py”, line 988, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File “errorhandling.py”, line 12, in get
raise tornado.web.HTTPError(400, ‘Page Not Found Error!!’)
HTTPError: HTTP 400: Bad Request (Page Not Found Error!!)
- WARNING:root:400 GET /articles/1 (127.0.0.1): Page Not Found Error!! —– Error description where web server is running
WARNING:root:400 GET /articles/1 (127.0.0.1) 10.68ms
Case2: self.send_error(500) is enabled
- ‘500: Internal Server Error’ web page shows up
- ERROR:root:500 GET /articles/1 (127.0.0.1) 0.41ms error line is generated where web server is running
Example:
https://gist.github.com/3249999.js