Skip to main content

Standardized error handling for Smart Platform FastAPI services

Project description

smart-errors

Standardized error handling for Smart Platform FastAPI services

Installation

pip install smart-errors

Or with uv:

uv add smart-errors

Quick Start

from fastapi import FastAPI
from mehdashti_errors import setup_error_handlers, NotFoundException

app = FastAPI()

# Setup error handlers (must be called early)
setup_error_handlers(app)

@app.get("/users/{user_id}")
async def get_user(user_id: str):
    user = await find_user(user_id)
    if not user:
        raise NotFoundException(f"User {user_id} not found")
    return user

Features

  • Problem Details Format: Compatible with RFC 7807 and @smart/contracts
  • Correlation ID: Automatic correlation ID extraction/generation
  • Field Validation: Converts Pydantic errors to standardized format
  • Logging Integration: Structured logging with loguru
  • Type Safe: Full typing support with Pydantic v2

Error Response Format

All errors follow this standardized format:

{
  "type": "not_found",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "User abc-123 not found",
  "instance": "/api/users/abc-123",
  "correlation_id": "xyz-789"
}

Validation Errors

{
  "type": "validation_error",
  "title": "Validation Failed",
  "status": 422,
  "detail": "One or more fields failed validation: 2 error(s)",
  "instance": "/api/users",
  "correlation_id": "xyz-789",
  "errors": [
    {
      "field": "email",
      "message": "value is not a valid email address",
      "code": "value_error.email"
    },
    {
      "field": "age",
      "message": "ensure this value is greater than 0",
      "code": "value_error.number.not_gt"
    }
  ]
}

Available Exceptions

Exception Status Error Type
ValidationException 422 validation_error
AuthenticationException 401 authentication_error
AuthorizationException 403 authorization_error
NotFoundException 404 not_found
ConflictException 409 conflict
RateLimitException 429 rate_limit_exceeded
BadRequestException 400 bad_request
InternalServerException 500 internal_error
ServiceUnavailableException 503 service_unavailable

Usage Examples

Basic Exception

from mehdashti_errors import NotFoundException

@app.get("/posts/{post_id}")
async def get_post(post_id: str):
    post = await db.get_post(post_id)
    if not post:
        raise NotFoundException(f"Post {post_id} not found")
    return post

With Field Errors

from mehdashti_errors import ValidationException, FieldError

@app.post("/users")
async def create_user(user_data: dict):
    errors = []

    if not user_data.get("email"):
        errors.append(FieldError(
            field="email",
            message="Email is required"
        ))

    if errors:
        raise ValidationException(
            detail="User validation failed",
            errors=errors
        )

    return await db.create_user(user_data)

With Metadata

from mehdashti_errors import ConflictException

@app.post("/users")
async def create_user(email: str):
    existing = await db.find_user_by_email(email)
    if existing:
        raise ConflictException(
            detail=f"User with email {email} already exists",
            meta={"existing_user_id": existing.id}
        )
    return await db.create_user(email)

Correlation ID

The package automatically extracts correlation IDs from the X-Correlation-Id header. If not present, it generates a new UUID.

# Client sends request with correlation ID
headers = {"X-Correlation-Id": "my-trace-id"}
response = requests.get("/api/users/123", headers=headers)

# Error response includes same correlation ID
{
  "type": "not_found",
  "status": 404,
  "correlation_id": "my-trace-id",
  ...
}

Integration with Logging

All errors are automatically logged with structured context:

# Logs include correlation_id, error_type, and metadata
logger.error(
    "not_found: User abc-123 not found",
    extra={
        "correlation_id": "xyz-789",
        "error_type": "not_found",
        "meta": {}
    }
)

Compatibility

  • Frontend: Works seamlessly with @smart/contracts error types
  • Backend: Compatible with FastAPI 0.115+
  • Python: Requires Python 3.11+

Development

# Install dev dependencies
uv sync --dev

# Run tests
pytest

# Type checking
mypy smart_errors

License

MIT

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

mehdashti_errors-0.2.0.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

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

mehdashti_errors-0.2.0-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file mehdashti_errors-0.2.0.tar.gz.

File metadata

  • Download URL: mehdashti_errors-0.2.0.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for mehdashti_errors-0.2.0.tar.gz
Algorithm Hash digest
SHA256 9c38b66635efc492690dceba54b10d078afba01ba2cae390e36f3c5498d8f8eb
MD5 ea0262e74dd19fd115fca5c9db7e86cd
BLAKE2b-256 15d29eef6741c65a7654ec777ab7bd495322d5ca6c440acc0139219efb62814a

See more details on using hashes here.

File details

Details for the file mehdashti_errors-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: mehdashti_errors-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.11 {"installer":{"name":"uv","version":"0.9.11"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for mehdashti_errors-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ac0509e67288d32163d74b4936170e9a132a44feef820516f489647c9a720f62
MD5 e830e9e13d0eeb583364293069722ea1
BLAKE2b-256 7bf22661928a5725144956dfe8bb5d82b1be1d6ea32c7842fc092f5c54210ef4

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