Elegant, consistent error handling for FastAPI applications
Project description
fastapi-error-handler
Elegant, consistent error handling for FastAPI — one line setup
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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_error_handler-0.1.0.tar.gz.
File metadata
- Download URL: fastapi_error_handler-0.1.0.tar.gz
- Upload date:
- Size: 7.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ca93fbd7c11fa1c53c8097c8e4d1c8c5042f3848c9e6d2d608928c569075463d
|
|
| MD5 |
f1d53038ff3955a5caa672bee59823fd
|
|
| BLAKE2b-256 |
96f4700b6d162b8bc969f37347c6b75cb2f950a7d15fd85b4091a08e28e4f1bc
|
File details
Details for the file fastapi_error_handler-0.1.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_error_handler-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
913a32aba8d3f70a3020b3d9db0493a1dede0a95cae4df305ddb84e32d2a819b
|
|
| MD5 |
d904ca9905e6691bfb7e4b53f98aa3af
|
|
| BLAKE2b-256 |
cd55143b97189a61b5d90051688f21c19a77705eab714936783bb0f36e2d7009
|