Skip to main content

fastapi-error-handler

Elegant, consistent error handling for FastAPI — one line setup

PyPI Python FastAPI License


The Problem

Every FastAPI app needs error handling. Without it, your API returns inconsistent, ugly responses:

{"detail": "Not Found"}
{"detail": [{"loc": ["body", "email"], "msg": "field required", "type": "value_error.missing"}]}
500 Internal Server Error

Different formats, missing context, no error codes. Your frontend team hates you.

The Solution

pip install fastapi-error-handler
from fastapi import FastAPI
from fastapi_error_handler import setup_error_handlers

app = FastAPI()
setup_error_handlers(app)  # That's it.

Now every error returns a clean, consistent JSON response:

{
    "error": "not_found",
    "message": "User with id '123' not found",
    "status": 404,
    "path": "/users/123"
}

Built-in Exceptions

Raise these anywhere in your routes — they automatically produce the right HTTP response:

from fastapi_error_handler import (
    NotFoundError,      # 404
    BadRequestError,    # 400
    UnauthorizedError,  # 401
    ForbiddenError,     # 403
    ConflictError,      # 409
    ValidationError,    # 422
    RateLimitError,     # 429
    InternalError,      # 500
)

@app.get("/users/{id}")
async def get_user(id: int):
    user = await db.get_user(id)
    if not user:
        raise NotFoundError("User", id=str(id))
    return user

@app.post("/users")
async def create_user(email: str):
    if await db.email_exists(email):
        raise ConflictError("A user with this email already exists")
    ...

What Gets Handled

Exception Status Response error field
NotFoundError 404 not_found
BadRequestError 400 bad_request
UnauthorizedError 401 unauthorized
ForbiddenError 403 forbidden
ConflictError 409 conflict
ValidationError 422 validation_error
RateLimitError 429 rate_limit_exceeded
InternalError 500 internal_error
Pydantic errors 422 validation_error (with field details)
Starlette HTTP any mapped from status code
Unhandled Exception 500 internal_error (safe message)

Configuration

setup_error_handlers(
    app,
    log_errors=True,       # Log 4xx as WARNING, 5xx as ERROR
    include_path=True,     # Include request path in response
    on_error=my_callback,  # Custom callback on every error
)

Custom Error Callback

def send_to_sentry(request, exc):
    sentry_sdk.capture_exception(exc)

setup_error_handlers(app, on_error=send_to_sentry)

Custom Exceptions

Extend AppError for domain-specific errors:

from fastapi_error_handler import AppError

class InsufficientBalanceError(AppError):
    status_code = 402
    error_code = "insufficient_balance"

    def __init__(self, balance: float, required: float):
        super().__init__(
            message=f"Insufficient balance: have {balance}, need {required}",
            details={"balance": balance, "required": required},
        )

Response Format

Every error response follows this schema:

{
    "error": "string",       // machine-readable error code
    "message": "string",     // human-readable message
    "status": 404,           // HTTP status code
    "path": "/users/123",    // request path (optional)
    "details": {}            // additional context (optional)
}

License

MIT

Release files for fastapi-error-handler 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-error-handler 0.1.0
File Size Uploaded
fastapi_error_handler-0.1.0.tar.gz 7.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-error-handler 0.1.0
File Interpreter ABI Platform
fastapi_error_handler-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 15.3 kB

Release files / fastapi_error_handler-0.1.0.tar.gz

Download URL fastapi_error_handler-0.1.0.tar.gz
Size 7.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ca93fbd7c11fa1c53c8097c8e4d1c8c5042f3848c9e6d2d608928c569075463d
BLAKE2b-256 checksum
How to use checksums
96f4700b6d162b8bc969f37347c6b75cb2f950a7d15fd85b4091a08e28e4f1bc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Release files / fastapi_error_handler-0.1.0-py3-none-any.whl

Download URL fastapi_error_handler-0.1.0-py3-none-any.whl
Size 7.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
913a32aba8d3f70a3020b3d9db0493a1dede0a95cae4df305ddb84e32d2a819b
BLAKE2b-256 checksum
How to use checksums
cd55143b97189a61b5d90051688f21c19a77705eab714936783bb0f36e2d7009
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.5

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release 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