Raise HTTPException for expected errors inside an endpoint (a status code plus detail), and register custom exception handlers when you want a consistent response format for a whole category of errors.
You can also override the handler for RequestValidationError to change the 422 response shape.
from fastapi import Request
from fastapi.responses import JSONResponse
class DatabaseError(Exception):
pass
@app.exception_handler(DatabaseError)
async def db_error_handler(request: Request, exc: DatabaseError):
return JSONResponse(status_code=503, content={"detail": "Database unavailable"})