Error handling and HTTPException

Difficulty: Beginner

Question

How does FastAPI handle errors? How do you raise HTTP errors and customise the error responses?

Answer

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).

The three kinds of errors

  1. Expected client errors: missing resource, wrong permissions, business rule violation. Raise HTTPException (404, 403, 409, etc.) or your own domain exception.
  2. Validation errors: bad path, query or body data. FastAPI raises RequestValidationError and returns 422 with a list of errors (loc, msg, type).
  3. Unexpected errors: bugs, a database outage. These become a plain 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.

Customising responses

  • HTTPException(detail=...) accepts any JSON-serializable value, so detail={"code": "INSUFFICIENT_BALANCE", "message": "..."} works.
  • Pass headers={"WWW-Authenticate": "Bearer"} or {"Retry-After": "30"} when the spec calls for it.
  • Register handlers for your own exceptions to keep services free of HTTP concerns: the service raises InsufficientBalance, the handler maps it to 402 or 409.
  • Override the default handlers for 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.
  • To keep the default behaviour and just add logging, import and call http_exception_handler or request_validation_exception_handler from fastapi.exception_handlers.

Choosing status codes

SituationCode
Malformed or semantically invalid input400 or 422
No or invalid credentials401
Authenticated but not allowed403
Resource does not exist (or you hide it)404
Conflict, e.g. duplicate email or stale version409
Rate limited429 with Retry-After
Downstream dependency failed502 or 503

Common mistakes

  • Returning {"error": ...} with status 200. Clients and monitoring then think the call succeeded.
  • Leaking stack traces or SQL errors in detail.
  • Catching 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.
  • Inconsistent shapes: some endpoints return detail, others error, others message. Pick one envelope (many teams follow RFC 9457 Problem Details) and enforce it with handlers.
From exception to error response. Exceptions raised anywhere in the request are routed to the matching handler.
  1. Handler or dependency raises: HTTPException or a domain exception.
  2. FastAPI catches it: Looks up a registered exception handler.
  3. Handler builds response: Status code, JSON body and headers.
  4. Unknown exceptions: Logged and returned as a generic 500.

Code examples

HTTPException, domain exceptions and a uniform error format

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.

Key points

  • Raise HTTPException for expected errors; it works from dependencies too
  • Validation failures raise RequestValidationError and return 422
  • Register handlers with @app.exception_handler to customise responses
  • Handle starlette's HTTPException to also cover routing 404/405
  • Never leak stack traces; log them with a request ID instead

Common follow-up questions

  • What is the difference between 401 and 403?
  • How would you add a request ID to every error response and log line?
  • Why would you register a handler for Starlette's HTTPException instead of FastAPI's?
  • What is RFC 9457 Problem Details?

Interview tips

  • Separate expected, validation and unexpected errors; it structures your answer well
  • Show that domain code should not import HTTP concepts, with handlers doing the mapping
  • Pick status codes carefully; using 401 vs 403 correctly is a quick credibility win

Concepts covered

HTTPException, exception_handler, RequestValidationError, custom exceptions, error response format

More FastAPI Interview questions