HTTP Exceptions

0.2.10 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define and raise HTTP exceptions within a function and then catch specific exception types to handle different HTTP error scenarios. All custom HTTP exceptions inherit from `HTTPException`.

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

view raw JSON →