Skip to main content

A comprehensive error handling library for Python applications with i18n support

Project description

Awesome Errors

A comprehensive Python library for standardized error handling, analysis, and documentation.

Architecture Overview

Core Components

1. Core Exceptions (src/awesome_errors/core/)

  • AppError: Base exception class for server-side error handling
  • ValidationError: HTTP 400 errors for input validation failures
  • AuthError: HTTP 401/403 errors for authentication/authorization
  • NotFoundError: HTTP 404 errors for missing resources
  • DatabaseError: HTTP 500/409/422 errors for database issues
  • BusinessLogicError: HTTP 422 errors for business rule violations

2. Client Exceptions (src/awesome_errors/client/)

  • BackendError: Client-side exception for handling server responses
  • ErrorResponseParser: Parser for backend error responses

Key Difference: Core exceptions are raised on the server, while client exceptions handle errors received from the server.

3. Error Converters (src/awesome_errors/converters/)

  • UniversalErrorConverter: Handles any type of exception
  • SQLErrorConverter: Converts SQLAlchemy errors
  • PythonErrorConverter: Converts standard Python exceptions
  • PydanticErrorConverter: Converts Pydantic validation errors
  • generic_error_handler: Shared logic for unknown errors

4. Analysis Tools (src/awesome_errors/analysis/)

  • ErrorAnalyzer: AST-based error analysis
  • analyze_errors: Decorator for automatic error analysis
  • openapi_errors: Decorator for OpenAPI documentation

5. HTTP Response Renderers (src/awesome_errors/core/renderers.py)

  • ErrorResponseRenderer: Produces either legacy envelopes or RFC 7807 documents
  • ErrorResponseFormat: Toggle between response formats per application

6. Framework Integrations (src/awesome_errors/middleware/)

  • FastAPI middleware: setup_error_handling
  • Litestar handlers: create_litestar_exception_handlers
  • Both integrations share their translation, logging, and exception-mapping logic via middleware/_base.py.

7. Internationalization (src/awesome_errors/i18n/)

  • ErrorTranslator: Multi-language error message support
  • English defaults are built in; additional locales load from src/awesome_errors/i18n/locales/ (importing the library never writes to disk)

Usage Examples

Server-Side Error Handling

from awesome_errors import ValidationError, NotFoundError, ErrorCode

# Validation error
raise ValidationError("Email is required", field="email")

# Not found error
raise NotFoundError("user", user_id=123)

# Custom error code
raise ValidationError("Invalid format", code=ErrorCode("CUSTOM_ERROR"))

Client-Side Error Handling

from awesome_errors import BackendError

try:
    response = api_client.get_user(123)
except BackendError as e:
    if e.is_not_found_error():
        print("User not found")
    elif e.is_validation_error():
        print("Invalid input")

FastAPI Integration

from fastapi import FastAPI
from awesome_errors import setup_error_handling, auto_analyze_errors

app = FastAPI()
setup_error_handling(app)

@auto_analyze_errors
@app.get("/users/{user_id}")
def get_user(user_id: int):
    if user_id == 404:
        raise NotFoundError("user", user_id)
    return {"id": user_id}

Litestar Integration

from litestar import Litestar
from awesome_errors import (
    ErrorResponseFormat,
    ErrorTranslator,
    create_litestar_exception_handlers,
)

translator = ErrorTranslator(default_locale="en")
translator.add_translations("en", {"CUSTOM": "Custom error"}, persist=False)

exception_handlers = create_litestar_exception_handlers(
    translator=translator,
    response_format=ErrorResponseFormat.RFC7807,
    problem_type_resolver=lambda err: f"urn:demo:error:{err.code.value.lower()}",
)

app = Litestar(route_handlers=[...], exception_handlers=exception_handlers)

Error Analysis

from awesome_errors import analyze_errors, openapi_errors

@analyze_errors()
def my_function():
    raise ValidationError("Test error")

@openapi_errors(additional_errors=["CUSTOM_ERROR"])
def my_api_endpoint():
    # Automatically documented in OpenAPI
    pass

Key Features

Unified Error Models

  • Lightweight msgspec structs used across server & client sides
  • Single serialization layer for legacy and RFC 7807 formats
  • Consistent error structure

Shared Generic Error Handling

  • Common generic_error_handler for unknown errors
  • Used by all converters to avoid code duplication
  • Debug mode support for detailed error information

Consolidated FastAPI Integration

  • Single entry point for all FastAPI integrations
  • Automatic OpenAPI documentation generation
  • Combined analysis and documentation decorators

Clean Architecture

  • Clear separation between server and client error handling
  • Modular converter system
  • Pluggable renderers for multiple frameworks

Internationalization Support

  • Multi-language error messages
  • Locale-based translation
  • Template parameter support
  • Optional persistence when extending translations at runtime

Installation

pip install awesome-errors

Development

# Install dependencies
uv sync --dev

# Run tests
uv run pytest

# Run linting
uv run ruff check src/

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

awesome_errors-0.4.0.tar.gz (36.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

awesome_errors-0.4.0-py3-none-any.whl (51.1 kB view details)

Uploaded Python 3

File details

Details for the file awesome_errors-0.4.0.tar.gz.

File metadata

  • Download URL: awesome_errors-0.4.0.tar.gz
  • Upload date:
  • Size: 36.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for awesome_errors-0.4.0.tar.gz
Algorithm Hash digest
SHA256 5b783c1c01e39b30e9ca2b9231788b334d135e6dc9a44461fdb79933318e5e8b
MD5 271cdd537dec1c0a84f79fc60e4a1e2e
BLAKE2b-256 a20cbdbb2a7f1dada68fcadadc0c342bca6397e48702aece8347d715bdce1424

See more details on using hashes here.

File details

Details for the file awesome_errors-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: awesome_errors-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 51.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for awesome_errors-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 36bc93cecf05d2113afc16b056adfff4fc8d87490902edba955592c362b9eaeb
MD5 2ed099920faebc3094e1fad3f159e15e
BLAKE2b-256 6e99a516b113b27435ce8808552d90b657c261858015f35c2d418734ea962110

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page