Requests Exceptions
requestsexceptions is a simple utility library designed to normalize the import paths for exceptions within the popular 'requests' HTTP library. It addresses scenarios where 'requests' might bundle 'urllib3' or be distributed with 'urllib3' unbundled, which can lead to inconsistencies when trying to catch specific exceptions like `urllib3.exceptions.HTTPError`. The library provides a unified way to import these exceptions, regardless of the underlying 'requests' packaging. Its current version is 1.4.0, released in February 2018, indicating a maintenance-focused cadence.
Warnings
- deprecated The `requestsexceptions` library was last updated in February 2018 (version 1.4.0). The 'requests' library has undergone significant development since then, including standardizing its internal exception handling (e.g., `requests.exceptions.JSONDecodeError` was introduced in `requests` 2.27.0).
- gotcha The primary problem `requestsexceptions` solves is the potential inconsistency in exception paths due to 'requests' bundling/unbundling `urllib3`. For many common use cases, especially with recent and stable 'requests' installations, directly importing from `requests.exceptions` is robust enough and may not require this extra abstraction.
- gotcha The library's long-term maintenance status is unclear, with its official GitHub being a mirror of opendev.org. No recent commits or releases indicate active development to keep pace with 'requests' library changes.
Install
-
pip install requestsexceptions
Imports
- ConnectionError
from requestsexceptions import ConnectionError
- HTTPError
from requestsexceptions import HTTPError
- Timeout
from requestsexceptions import Timeout
- RequestException
from requestsexceptions import RequestException
Quickstart
import requests
from requestsexceptions import ConnectionError, Timeout, HTTPError, RequestException
def fetch_url(url):
try:
response = requests.get(url, timeout=1)
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
print(f"Successfully fetched {url}, status: {response.status_code}")
except ConnectionError:
print(f"Connection error occurred for {url}.")
except Timeout:
print(f"Request timed out for {url}.")
except HTTPError as e:
print(f"HTTP error for {url}: {e.response.status_code}")
except RequestException as e:
print(f"An unexpected Requests error occurred for {url}: {e}")
except Exception as e:
print(f"An non-Requests error occurred for {url}: {e}")
fetch_url('https://httpbin.org/status/200')
fetch_url('https://httpbin.org/status/404')
fetch_url('http://nonexistent.domain.xyz')
fetch_url('https://httpbin.org/delay/5')