HTTP Exceptions
http-exceptions is a Python library that provides a set of raisable HTTP status code exceptions, making it easy to integrate standardized HTTP error handling into web applications and APIs. It's currently at version 0.2.10 and sees active maintenance with frequent minor releases focusing on features, fixes, and build improvements.
Common errors
-
ModuleNotFoundError: No module named 'http_exceptions'
cause Incorrect library name used in the import statement, or the package was not installed.fixVerify the package is installed with `pip install http-exceptions` and that the import uses an underscore: `from http_exceptions import HTTPException`. -
TypeError: __init__() missing 1 required positional argument: 'detail'
cause Attempted to raise an HTTP exception without providing the mandatory `detail` argument.fixProvide a descriptive string for the `detail` argument: `raise BadRequest(detail='User provided invalid data.')`. -
AttributeError: 'HTTPException' object has no attribute 'status_code'
cause This error is unlikely with `http-exceptions` as `status_code` is always present. More likely, you're catching a generic `Exception` which isn't an `HTTPException` or a subclass.fixEnsure you are catching `HTTPException` or a specific subclass and not a generic `Exception` if you intend to access `status_code` or `detail` attributes. Example: `except HTTPException as e:`.
Warnings
- gotcha When raising `HTTPException` or any of its subclasses, the `detail` argument is mandatory. Omitting it will result in a `TypeError` as it's not optional.
- gotcha For Python versions prior to 3.8, `importlib-metadata` is a required dependency. While `pip install http-exceptions` should handle this automatically, issues might arise in constrained environments or older `pip` versions.
- gotcha The library name on PyPI (`http-exceptions`) differs slightly from the import path (`http_exceptions`). Be careful with underscores vs. hyphens.
Install
-
pip install http-exceptions
Imports
- HTTPException
from http_exceptions import HTTPException
- BadRequest
from http_exceptions import BadRequest
- NotFound
from http_exceptions import NotFound
- Forbidden
from http_exceptions import Forbidden
- Unauthorized
from http_exceptions import Unauthorized
- InternalServerError
from http_exceptions import InternalServerError
Quickstart
from http_exceptions import BadRequest, NotFound, HTTPException
def get_user_data(user_id: str):
if not user_id.isdigit():
raise BadRequest(detail="User ID must be a numeric string.")
if user_id == "404":
raise NotFound(detail=f"User with ID '{user_id}' not found.")
if user_id == "500":
raise HTTPException(status_code=500, detail="Internal server error processing user.")
return {"id": user_id, "name": f"User {user_id}"}
# Example usage and error handling
try:
user = get_user_data("abc")
except BadRequest as e:
print(f"Caught error: {e.status_code} - {e.detail}")
try:
user = get_user_data("404")
except NotFound as e:
print(f"Caught error: {e.status_code} - {e.detail}")
try:
user = get_user_data("500")
except HTTPException as e:
print(f"Caught generic HTTP error: {e.status_code} - {e.detail}")
try:
user = get_user_data("123")
print(f"Successfully retrieved user: {user}")
except HTTPException:
pass # Should not happen here