Skip to main content

voltwire-fastapi-exceptions

Reusable exception handling for FastAPI apps: a base AppError hierarchy you can raise (and extend), plus a middleware + validation handler so that every error — raised before, during, or after the route — reaches the client as the same JSON body.

Bring your own response model. The library never defines or imposes a response schema — you pass your own model down, and the handlers use only the slice they need (construct it with message + errors, then call .model_dump()). Your app keeps one model for both success and error responses; nothing is coupled across the boundary.

Installation

pip install voltwire-fastapi-exceptions
# or with Poetry:
poetry add voltwire-fastapi-exceptions

Raising errors

Raise an AppError (or a subclass) anywhere; the middleware turns it into your response model with the right status code.

from voltwire.fastapi.exceptions import EntityNotFoundError, ForbiddenError

def get_user(user_id: str):
    user = repo.find(user_id)
    if not user:
        raise EntityNotFoundError(f"No user {user_id}")   # -> 404
    if not user.active:
        raise ForbiddenError()                            # -> 403
    return user

Built-in classes: UnauthorizedRequestError (401), ForbiddenError (403), BadRequestError (400), EntityNotFoundError (404), ResourceConflictError (409), UnprocessableRequestError (422), UnsupportedFeatureError (501), DownstreamServiceError (502).

AppWarning is an AppError subclass for expected/recoverable conditions — logged at warning level instead of error. ForbiddenError and UnsupportedFeatureError are warnings.

Extend them

from voltwire.fastapi.exceptions import UnprocessableRequestError

class DivideByZeroError(UnprocessableRequestError):
    def __init__(self, message="Cannot divide by zero"):
        super().__init__(message)

Your response model

Provide any model whose instances have a .model_dump() and that can be constructed with message= and errors= (a pydantic model with those two fields — plus whatever else you want, e.g. timestamp, metadata — is the common case). The library only ever sets message and errors; the rest come from your model's defaults. This is the ApiErrorBody protocol:

class ApiErrorBody(Protocol):
    def __init__(self, *, message: str, errors: list[str]) -> None: ...
    def model_dump(self, *, mode: str = "json", exclude_none: bool = True) -> dict: ...

Wiring it into your app

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from voltwire.fastapi.exceptions import (
    ExceptionMiddleware,
    DefaultExceptionHandlerSettings,
    build_validation_handler,
    build_error_responses,
)
from myapp.models import ApiMessage   # <-- YOUR model

app = FastAPI(responses=build_error_responses(ApiMessage))   # OpenAPI error schemas

# Catches AppError (-> its status) and any unexpected Exception (-> 500).
app.add_middleware(
    ExceptionMiddleware,
    error_model=ApiMessage,
    settings=DefaultExceptionHandlerSettings(production=is_production()),
)

# RequestValidationError is raised during request parsing, before the middleware runs,
# so register it as an exception handler too — same body, built from your model.
app.add_exception_handler(RequestValidationError, build_validation_handler(ApiMessage))

Settings (why not read your env directly?)

The middleware only needs to know one thing: are we in production? (In production the 500 handler hides the raw exception string; otherwise it includes it to aid debugging.)

Rather than force a settings system on you, it takes any object matching the ExceptionHandlerSettings protocol — a single production: bool. Use the provided DefaultExceptionHandlerSettings, or pass your own object exposing production.

Download files

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

Source Distribution

voltwire_fastapi_exceptions-0.0.2.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

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

voltwire_fastapi_exceptions-0.0.2-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file voltwire_fastapi_exceptions-0.0.2.tar.gz.

File metadata

  • Download URL: voltwire_fastapi_exceptions-0.0.2.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.24 {"installer":{"name":"uv","version":"0.9.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for voltwire_fastapi_exceptions-0.0.2.tar.gz
Algorithm Hash digest
SHA256 67736e525b1015c6592e4cd8a2c0bdaced7f909932320986414f06a57bcc5f4e
MD5 1f95fcbe4474011945d9c7da8ae92197
BLAKE2b-256 0d42227688dcac7c53dbcee6056de8fa4e022c5d574c298254a2675f48566b60

See more details on using hashes here.

File details

Details for the file voltwire_fastapi_exceptions-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: voltwire_fastapi_exceptions-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 5.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.24 {"installer":{"name":"uv","version":"0.9.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for voltwire_fastapi_exceptions-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1f330f10fba9141a8ab10ff69a2e02f1f199a87c47211467df5a82c6aafe3382
MD5 724ccff0367fa7ed36a19dd344064756
BLAKE2b-256 594c139c349a84446caaaf96473ab5f3c1b79855dd1ba8688336d21383f8991b

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.0.2 This release

2 files

0.0.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page