Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)
Centralized Exception Handling in FastAPI:
In Simple Words: Catch custom domain exceptions globally and transform them into standardized JSON error responses.
python
from fastapi import Request
from fastapi.responses import JSONResponse
class ItemNotFoundError(Exception):
def __init__(self, item_id: int): self.item_id = item_id
@app.exception_handler(ItemNotFoundError)
async def item_not_found_handler(request: Request, exc: ItemNotFoundError):
return JSONResponse(
status_code=404,
content={"error": "ITEM_NOT_FOUND", "item_id": exc.item_id}
)