Full answer
FastAPI already turns HTTPException into {"detail": ...} and validation failures into a 422 list. Larger APIs often want one consistent error shape and cleaner service code.
Handlers:
@app.exception_handler(NoCopiesLeft)
async def no_copies(request: Request, exc: NoCopiesLeft):
return JSONResponse(status_code=409, content={"error": {"code": "NO_COPIES", "message": str(exc)}})Domain exceptions: services raise meaningful exceptions (StudentNotFound, FeeAlreadyPaid) without importing FastAPI. Handlers translate them into HTTP responses in one place. This keeps business logic reusable from CLI scripts or workers.
Validation errors: override RequestValidationError to reshape the default 422 body, for example into {"error": {"code": "VALIDATION_ERROR", "fields": {...}}}. exc.errors() gives the list of Pydantic errors with loc, msg, type. Keep the details; clients need to know which field failed. fastapi.exception_handlers.request_validation_exception_handler lets you log and then call the default.
HTTP errors: register a handler for starlette.exceptions.HTTPException (the parent of FastAPI's) to cover 404s for unknown routes and 405s too, not only the ones you raise.
Unexpected errors: an Exception handler can log with a request ID and return a generic 500 body. Never return stack traces or SQL errors to clients. Note that Starlette's ServerErrorMiddleware handles Exception handlers outside other middleware, and the exception still re-raises for the server log.
Standard formats: RFC 9457 "Problem Details for HTTP APIs" (application/problem+json with type, title, status, detail) is a widely understood shape if your organisation has no standard.
Document error responses in route responses= so the OpenAPI schema matches reality.
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
class NoCopiesLeft(Exception):
def __init__(self, title: str):
super().__init__(f"No copies of '{title}' are available")
def error(status: int, code: str, message: str, **extra):
return JSONResponse(status_code=status, content={"error": {"code": code, "message": message, **extra}})
@app.exception_handler(NoCopiesLeft)
async def handle_no_copies(request: Request, exc: NoCopiesLeft):
return error(409, "NO_COPIES", str(exc))
@app.exception_handler(RequestValidationError)
async def handle_validation(request: Request, exc: RequestValidationError):
fields = {".".join(str(p) for p in e["loc"][1:]): e["msg"] for e in exc.errors()}
return error(422, "VALIDATION_ERROR", "Some fields are invalid", fields=fields)
@app.exception_handler(StarletteHTTPException)
async def handle_http(request: Request, exc: StarletteHTTPException):
return error(exc.status_code, f"HTTP_{exc.status_code}", str(exc.detail))
@app.exception_handler(Exception)
async def handle_unexpected(request: Request, exc: Exception):
return error(500, "INTERNAL_ERROR", "Something went wrong. Please try again.")
class IssueIn(BaseModel):
roll_no: str = Field(min_length=3)
days: int = Field(ge=1, le=30)
def issue_book(title: str): # service layer: no FastAPI imports needed
raise NoCopiesLeft(title)
@app.post("/books/{title}/issue")
def issue(title: str, data: IssueIn):
issue_book(title)
@app.get("/crash")
def crash():
raise ZeroDivisionError("secret internal detail")
c = TestClient(app, raise_server_exceptions=False)
print(c.post("/books/Godan/issue", json={"roll_no": "BCA-17", "days": 7}).json())
print(c.post("/books/Godan/issue", json={"roll_no": "B", "days": 90}).json())
print(c.get("/no-such-page").json())
print(c.get("/crash").status_code, c.get("/crash").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. raise_server_exceptions=False makes TestClient return the 500 response instead of re-raising the error in the test. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'error': {'code': 'NO_COPIES', 'message': "No copies of 'Godan' are available"}} {'error': {'code': 'VALIDATION_ERROR', 'message': 'Some fields are invalid', 'fields': {'roll_no': 'String should have at least 3 characters', 'days': 'Input should be less than or equal to 30'}}} {'error': {'code': 'HTTP_404', 'message': 'Not Found'}} 500 {'error': {'code': 'INTERNAL_ERROR', 'message': 'Something went wrong. Please try again.'}}
Key points
- @app.exception_handler maps exception types to responses
- Domain exceptions keep services free of HTTP code
- Override RequestValidationError to reshape 422 bodies
- Handle Starlette's HTTPException to cover framework 404/405
- Catch-all handler logs and hides internals
Common mistakes
- Returning stack traces or database error text to clients
- Throwing away field details when reshaping validation errors
- Raising HTTPException deep inside service code that should not know about HTTP
- Handling only FastAPI's HTTPException and missing framework-level 404 and 405 errors
Follow-ups
- How would you add a request ID to every error response?
- What is RFC 9457 Problem Details?
- Where would you log unexpected errors, and with what context?
Tips
- Show domain exceptions plus a handler, the cleanest architecture point
- Mention RequestValidationError by name
- Stress not leaking internals