Exception Handling Of Python Requests Module
The aim of this playbook🏁 is to share a personal template for exception handling of the Python requests module.
First things first: what is not stressed enough is that if you want to raise an exception for 4xx/5xx HTTP status errors, you need the raise_for_status() method.
HTTPError alone does not catch 4xx/5xx (e.g. also authentication failures, server outages that return with 5xx, etc.)
Also, in code around me, I am regularly finding something like which is not enough
response = requests.get(url, auth=token)
print("ERROR: Failed to establish connection")
- first, a personal real-life code I am using for the deletion of a document from Zendesk Guide (Knowledge base)
HTTPErroris (also) raised by
response.raise_for_status()- if the HTTP Request returned an unsuccesful status code (
- exceptions that Requests explicitly raises inherit from
- The official Requests exception docs offer more fine tuned exception types
- in other words and if need be, create a dedicated exception block for each error type as the following example from SO