⚙️ Python Backend Patterns — Centralized Exception Handling 🐍
Posted on: November 9, 2026
Description:
A missing product, unavailable stock, and a programming bug are different failures. Clients should receive meaningful HTTP statuses through a predictable response structure. Centralised exception handling keeps that translation at the API boundary instead of duplicating it across endpoints.
Describe the business failure
Define ordinary Python exceptions. They do not need to know about FastAPI, JSON, or HTTP status codes.
class DomainError(Exception):
pass
class ProductNotFound(DomainError):
pass
class OutOfStock(DomainError):
pass
The service raises the appropriate exception:
product = catalog.get(product_id)
if product is None:
raise ProductNotFound()
if product["stock"] <= 0:
raise OutOfStock()
This example checks availability only. It neither reserves stock nor makes a concurrent purchase safe.
Translate at the API boundary
Keep an explicit mapping in the API layer:
ERROR_MAP = {
ProductNotFound: (404, "PRODUCT_NOT_FOUND", "Product not found."),
OutOfStock: (409, "OUT_OF_STOCK", "Product is out of stock."),
}
404 represents an absent product. Here, 409 represents a conflict with current stock state. Choose statuses according to the operation's semantics, not a universal exception-to-status rule.
Register one handler for the domain base class:
@app.exception_handler(DomainError)
async def domain_error_handler(request, exc):
translated = ERROR_MAP.get(type(exc))
if translated is None:
return await unexpected_error_handler(request, exc)
return error_response(*translated)
The map matches exact types. New public exception subclasses need an explicit entry; unmapped domain errors take the safe 500 path.
Use one error shape
The shared builder produces JSON with a stable machine-readable code and a human-readable message:
def error_response(status, code, message, headers=None):
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message}},
headers=headers,
)
For a missing product, the HTTP status is 404 and the body is:
{"error": {"code": "PRODUCT_NOT_FOUND", "message": "Product not found."}}
Clients can branch on code without parsing message text. This is a simple application-specific contract, not an implementation of the Problem Details standard.
Include framework and unexpected errors
A domain handler alone does not normalise every failure. The complete script also registers handlers for request validation and Starlette HTTP exceptions, preserving HTTP exception headers such as Allow.
Unexpected exceptions are logged server-side and return 500 with INTERNAL_ERROR and “Something went wrong.” Keep debug=False; never put raw exception text into public responses. Server logs still require access controls and redaction. Only catch locally when you can recover, add useful context, or perform cleanup.
This example covers ordinary request failures before a response starts. Background-task failures, partially sent streaming responses, proxies, and server startup failures require their own handling and cannot always be replaced by this JSON response. Handler registration also does not automatically document every error response in OpenAPI.
Run and verify
python -m pip install -r requirements.txt
python centralized_exception_handling.py
python test_example.py
# Optional live API:
uvicorn centralized_exception_handling:app --reload
| Request | Status | Result |
|---|---|---|
/products/1/availability |
200 | Available |
/products/999/availability |
404 | PRODUCT_NOT_FOUND |
/products/2/availability |
409 | OUT_OF_STOCK |
/products/bad/availability |
422 | INVALID_REQUEST |
| Dependency failure injected by the test | 500 | INTERNAL_ERROR |
Tests also check unknown routes, method errors and preserved headers, absence of internal diagnostics in the 500 body, and restoration after the injected failure. raise_server_exceptions=False lets TestClient inspect the 500 response instead of re-raising the server exception.
The result is a small separation of responsibilities: services describe failures; the API translates them; clients receive a predictable contract.
Code Snippet:
import json
import logging
from typing import Annotated
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from starlette.exceptions import HTTPException
logger = logging.getLogger(__name__)
# 1. Domain errors describe business failures, without HTTP dependencies.
class DomainError(Exception):
pass
class ProductNotFound(DomainError):
pass
class OutOfStock(DomainError):
pass
def get_catalog() -> dict[int, dict]:
return {1: {"name": "Notebook", "stock": 3},
2: {"name": "Pen", "stock": 0}}
def check_availability(product_id: int, catalog: dict[int, dict]) -> dict:
product = catalog.get(product_id)
if product is None:
raise ProductNotFound()
if product["stock"] <= 0:
raise OutOfStock()
return {"product_id": product_id, "available": True}
# 2. HTTP translation belongs to the API layer, not the domain classes.
app = FastAPI(debug=False)
ERROR_MAP = {
ProductNotFound: (404, "PRODUCT_NOT_FOUND", "Product not found."),
OutOfStock: (409, "OUT_OF_STOCK", "Product is out of stock."),
}
def error_response(status: int, code: str, message: str,
headers: dict[str, str] | None = None) -> JSONResponse:
return JSONResponse(status_code=status,
content={"error": {"code": code, "message": message}},
headers=headers)
@app.exception_handler(DomainError)
async def domain_error_handler(request: Request, exc: DomainError):
# Exact-type map: explicitly register each public domain error.
translated = ERROR_MAP.get(type(exc))
if translated is None:
return await unexpected_error_handler(request, exc)
return error_response(*translated)
# 3. Normalize framework failures through the same response builder.
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(422, "INVALID_REQUEST", "Request validation failed.")
@app.exception_handler(HTTPException)
async def http_error_handler(request: Request, exc: HTTPException):
message = {404: "Route not found.", 405: "Method not allowed."}.get(
exc.status_code, "Request failed.")
return error_response(exc.status_code, f"HTTP_{exc.status_code}",
message, headers=exc.headers)
@app.exception_handler(Exception)
async def unexpected_error_handler(request: Request, exc: Exception):
# Traceback stays server-side. Never expose str(exc) to clients.
# Production logs still need restricted access and redaction policies.
logger.error("Unhandled API error", exc_info=(type(exc), exc, exc.__traceback__))
return error_response(500, "INTERNAL_ERROR", "Something went wrong.")
# 4. The endpoint contains no repeated try/except response formatting.
@app.get("/products/{product_id}/availability")
def availability(product_id: int,
catalog: Annotated[dict[int, dict], Depends(get_catalog)]):
return check_availability(product_id, catalog)
# 5. Exercise real request handling in-process, without starting a server.
if __name__ == "__main__":
with TestClient(app, raise_server_exceptions=False) as client:
for product_id in (1, 999, 2, "bad"):
response = client.get(f"/products/{product_id}/availability")
print(response.status_code, json.dumps(response.json()))
No comments yet. Be the first to comment!