Difficulty: Beginner
How does FastAPI handle errors? How do you raise HTTP errors and customise the error responses?
In FastAPI you signal an expected error by raising HTTPException(status_code=..., detail=...), which stops the handler and returns a JSON response like {"detail": "Order not found"} with that status code. Validation failures are raised automatically as RequestValidationError (a 422), and you can change how any exception is turned into a response by registering a handler with @app.exception_handler(SomeException).
HTTPException (404, 403, 409, etc.) or your own domain exception.RequestValidationError and returns 422 with a list of errors (loc, msg, type).500 Internal Server Error and the traceback goes to the server logs, never to the client.Because HTTPException is an exception, you can raise it from deep inside a dependency or a helper function and it still becomes a proper response. That is why auth checks live in dependencies.
HTTPException(detail=...) accepts any JSON-serializable value, so detail={"code": "INSUFFICIENT_BALANCE", "message": "..."} works.headers={"WWW-Authenticate": "Bearer"} or {"Retry-After": "30"} when the spec calls for it.InsufficientBalance, the handler maps it to 402 or 409.RequestValidationError or Starlette's HTTPException to enforce one error format across the API. Register the handler for starlette.exceptions.HTTPException so it also catches 404s and 405s raised by routing.http_exception_handler or request_validation_exception_handler from fastapi.exception_handlers.| Situation | Code |
|---|---|
| Malformed or semantically invalid input | 400 or 422 |
| No or invalid credentials | 401 |
| Authenticated but not allowed | 403 |
| Resource does not exist (or you hide it) | 404 |
| Conflict, e.g. duplicate email or stale version | 409 |
| Rate limited | 429 with Retry-After |
| Downstream dependency failed | 502 or 503 |
{"error": ...} with status 200. Clients and monitoring then think the call succeeded.detail.Exception in every handler and swallowing errors. Let unexpected errors bubble up to one global handler that logs with a request ID and returns a generic 500.detail, others error, others message. Pick one envelope (many teams follow RFC 9457 Problem Details) and enforce it with handlers.import logging
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
log = logging.getLogger("api")
app = FastAPI()
class InsufficientBalance(Exception): # domain error, no HTTP knowledge
def __init__(self, needed_paise: int):
self.needed_paise = needed_paise
@app.exception_handler(InsufficientBalance)
async def insufficient_balance_handler(request: Request, exc: InsufficientBalance):
return JSONResponse(status_code=409, content={
"code": "INSUFFICIENT_BALANCE",
"message": f"Need {exc.needed_paise} more paise",
})
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
return JSONResponse(status_code=422, content={
"code": "VALIDATION_FAILED",
"errors": [{"field": ".".join(map(str, e["loc"])), "msg": e["msg"]} for e in exc.errors()],
})
@app.exception_handler(Exception)
async def unhandled_handler(request: Request, exc: Exception):
log.exception("Unhandled error on %s", request.url.path)
return JSONResponse(status_code=500, content={"code": "INTERNAL_ERROR"})
@app.post("/wallet/{wallet_id}/pay")
def pay(wallet_id: int, amount_paise: int):
if wallet_id != 1:
raise HTTPException(status_code=404, detail="Wallet not found")
balance = 5000
if amount_paise > balance:
raise InsufficientBalance(needed_paise=amount_paise - balance)
return {"status": "paid"}
The service-level exception stays free of HTTP details and a handler maps it to 409. The validation and catch-all handlers enforce one consistent error shape and keep tracebacks out of responses.
HTTPException, exception_handler, RequestValidationError, custom exceptions, error response format