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.

The 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

try:
response = requests.get(url, auth=token)
except:
print("ERROR: Failed to establish connection")
raise
  • exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException
  • The official Requests exception docs offer more fine tuned exception types

SOURCES

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com