Requests - Working with Errors

This chapter will discuss how to deal with errors coming down when working with the Http request library. It is always a good practice to have errors managed for all possible cases.

Error Exception

The requests module gives the following types of error exception −

ConnectionError − This will be raised, if there is any connection error. For example, the network failed, DNS error so the Request library will raise ConnectionError exception.

Response.raise_for_status() − Based on status code i.e. 401, 404 it will raise HTTPError for the url requested.

HTTPError − This error will be raised for an invalid response coming down for the request made.

Timeout − Errors raised for a timeout for the URL requested.

TooManyRedirects − If the limit is crossed for maximum redirections than it will raise TooManyRedirects error.


Here is an example of errors shown for timeout −

import requests
getdata = 


raise ConnectTimeout(e, request=request)
HTTPSConnectionPool(host='jsonplaceholder.ty', port=443): Max retries exceeded with url: /users (Caused
by Connect
TimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at
E76A0>, 'Connection to timed out. (connect 
timeout = 0.001)'))