Chapter 2
There are a number of codes, and each one conveys a different meaning. According
to their first digit, status codes are classified into the following groups:
- 100: Informational
- 200: Success
- 300: Redirection
- 400: Client error
- 500: Server error
A few of the more frequently encountered codes and their messages are as follows:
- 200 : OK
- 404 : Not Found
- 500 : Internal Server Error
The official list of status codes is maintained by IANA and it can be found at
https://www.iana.org/assignments/http-status-codes. We'll be looking
at various codes in this chapter.
Handling problems
Status codes help us to see whether our response was successful or not. Any code in
the 200 range indicates a success, whereas any code in either the 400 range or the 500
range indicates failure.
Status codes should always be checked so that our program can respond
appropriately if something goes wrong. The urllib package helps us in
checking the status codes by raising an exception if it encounters a problem.
Let's go through how to catch these and handle them usefully. For this try the
following command block:
import urllib.error
from urllib.request import urlopen
try:
... urlopen('http://www.ietf.org/rfc/rfc0.txt')
... except urllib.error.HTTPError as e:
... print('status', e.code)