fastapi-exceptions

v0.0.1

Global exception handling module and demo error endpoints for FastAPI recipes.

_ _signor_p_ ยท 0 downloads ยท Updated 8/1/2026
fastapiexceptionserror-handlingmiddlewarerecipe
xnex install fastapi-exceptions GitHub repo

FastAPI Global Exception Handling Recipe

This recipe provides a fully decoupled, enterprise-grade exception handling system. It removes the boilerplate of writing custom error classes and standardizes error responses across your entire API.


๐Ÿ“ฆ What's Included

  • app/core/exceptions.py: Contains CustomAppException class and global error handlers (HTTP 400, HTTP 500).
  • app/api/endpoints/demo_error.py: Pre-configured demo controller to verify the error pipeline.

โšก 2-Step Wiring (Connecting the Recipe)

Since xnex safely injects these modules without mutating your existing codebase, you simply need to connect them in your app entrypoints:

Step 1: Register Handlers in app/main.py

Import register_exception_handlers and bind it to your primary FastAPI app instance:

python
from fastapi import FastAPI
from core.config import settings
from api.router import api_router
# 1. Import the exception registrar
from core.exceptions import register_exception_handlers

app = FastAPI(title=settings.PROJECT_NAME)

# 2. Register exception handlers (Add this line)
register_exception_handlers(app)

app.include_router(api_router, prefix=settings.API_STR)

Step 2: (Optional) Register Demo Router in app/api/router.py

To test and see the error responses in Swagger/Postman, include the demo endpoints:

python
from fastapi import APIRouter
from api.endpoints import health, demo_error  # Import demo_error

api_router = APIRouter()

api_router.include_router(health.router, tags=["Health"])
# Add demo error router
api_router.include_router(demo_error.router, prefix="/demo", tags=["Demo Errors"])

๐Ÿ’ก How to Use in Your Business Logic

Whenever an error occurs in your services or endpoints, raise CustomAppException instead of generic Python errors:

python
from fastapi import APIRouter
from core.exceptions import CustomAppException

router = APIRouter()

@router.get("/users/{user_id}")
async def get_user(user_id: int):
    if user_id <= 0:
        # Throw custom error with custom status code
        raise CustomAppException(
            message="Invalid User ID provided.",
            status_code=400
        )
    return {"user_id": user_id}

Standardized JSON Output

Clients will receive a uniform structure every time an error happens:

json
{
  "success": false,
  "error": "ApplicationError",
  "message": "Invalid User ID provided.",
  "path": "/api/users/-1"
}