af-fastapi-exceptions
Reusable exception handling for FastAPI apps: a base ServiceError 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 af-fastapi-exceptions
# or with Poetry:
poetry add af-fastapi-exceptions
Raising errors
Raise a ServiceError (or a subclass) anywhere; the middleware turns it into your response
model with the right status code.
from allfly.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).
ServiceWarning is a ServiceError subclass for expected/recoverable conditions — logged
at warning level instead of error. ForbiddenError and UnsupportedFeatureError are
warnings.
Extend them
from allfly.fastapi.exceptions import UnprocessableRequestError
class FopError(UnprocessableRequestError):
def __init__(self, message="Payment method was rejected."):
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 allfly.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 ServiceError (-> 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.
Logging
Handlers log via loguru — ServiceWarning at warning,
real errors at error/exception. If your app doesn't configure loguru, the messages are
simply not emitted at higher levels by default.
Metadata
Release files for af-fastapi-exceptions 0.0.6
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| af_fastapi_exceptions-0.0.6.tar.gz | 4.4 kB | With provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| af_fastapi_exceptions-0.0.6-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 10.4 kB
Release files / af_fastapi_exceptions-0.0.6.tar.gz
| Download URL | af_fastapi_exceptions-0.0.6.tar.gz |
|---|---|
| Size | 4.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
166e95b8a821382f28d3c3458cbe80567f636918dfe545ee4b910c13816bce3a
|
|
BLAKE2b-256 checksum How to use checksums |
290fd88ee65b4fc670efc696b7f8ec9d2724838fd7a4bd41dcd0ee9285c649cb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.
Transparency logRelease files / af_fastapi_exceptions-0.0.6-py3-none-any.whl
| Download URL | af_fastapi_exceptions-0.0.6-py3-none-any.whl |
|---|---|
| Size | 6.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
fef5a52a5a311f174d97fe048e63d6d02bc3cc93a28c204ccd5571033875cc11
|
|
BLAKE2b-256 checksum How to use checksums |
7af6d87215a7ba0cd8548261c95b7966a41397fb4b8ee2490bed1de3dceca627
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.
Transparency logSecurity for af-fastapi-exceptions 0.0.6
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 2 files in this release have been uploaded with provenance metadata.
Attestation for af_fastapi_exceptions-0.0.6.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.