skip to content

In FastAPI, how do you turn a custom InsufficientFunds exception into a 409 JSON response, and what must the exception handler accept and return?

level: middleimportance: should knowfreq 50%

answer

  1. register on the app
  2. request first, exception second
  3. a Response object, not a dict
  4. lookup follows the class MRO

basics

~20 s

Register a function taking (request, exc) with @app.exception_handler(InsufficientFunds) and return a Response such as JSONResponse(status_code=409, content=...). FastAPI finds it by walking the raised exception's class MRO, so a handler on a base class covers subclasses.

solid answer

~40 s

The domain code raises `InsufficientFunds` with no HTTP knowledge, and the app registers `@app.exception_handler(InsufficientFunds)` on an `async def handler(request: Request, exc: InsufficientFunds)`. The handler must return a response object, usually `JSONResponse(status_code=409, content={...})`; a plain dict is not serialized the way a path operation's return value is, and the request ends as a 500. Handlers are looked up along the raised class's MRO, so one handler on a `PaymentError` base serves every subclass. Registration lives on the `FastAPI` app (the decorator, `add_exception_handler` or `exception_handlers=`), not on an `APIRouter`. A key of `Exception` or `500` is special: it goes to the outermost server-error middleware, which re-raises after responding.

code

python · 34 lines
python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()


class PaymentError(Exception):
    status_code = 400
    code = "PAYMENT_ERROR"


class InsufficientFunds(PaymentError):
    status_code = 409
    code = "INSUFFICIENT_FUNDS"

    def __init__(self, account_id: str, shortfall: int):
        self.account_id = account_id
        self.shortfall = shortfall


@app.exception_handler(PaymentError)
async def payment_error_handler(request: Request, exc: PaymentError):
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": {"code": exc.code, "message": "The payment was refused"}},
    )


@app.post("/accounts/{account_id}/withdrawals")
async def withdraw(account_id: str, amount: int):
    balance = 100
    if amount > balance:
        raise InsufficientFunds(account_id, shortfall=amount - balance)
    return {"balance": balance - amount}

go deeper

for a junior

Recall the decorator, the (request, exc) signature and that the handler returns a JSONResponse with the status you choose.

for a middle

Explain MRO-based lookup, integer status keys matching only HTTPException, the three registration forms, and why a returned dict fails.

for a senior

Know the reach: app-level only, not your own middleware, not a started stream, and Exception handlers re-raising after the 500.

for a principal

Decide where HTTP mapping lives so domain code stays framework-free, and which exception base classes the team maps once at the edge.

## Why map exceptions instead of raising `HTTPException` everywhere A service layer that debits accounts should not know about status codes. Raising a domain exception such as `InsufficientFunds(account_id, shortfall)` keeps that code reusable from a task or a script, and one **exception handler** registered on the FastAPI app translates it to HTTP at the edge. ## Registering the handler FastAPI offers three equivalent ways, all on the **application** object: 1. the decorator `@app.exception_handler(InsufficientFunds)`; 2. the method `app.add_exception_handler(InsufficientFunds, handler)`; 3. the constructor argument `FastAPI(exception_handlers={InsufficientFunds: handler})`. `APIRouter` has no handler registry in FastAPI 0.143. Handlers are application-wide; a router-specific error format needs a separately mounted application or a check inside the handler. ## What the handler accepts and returns | Aspect | Rule | |---|---| | Parameters | the Starlette `Request`, then the exception instance | | Return value | a response object: `JSONResponse`, `PlainTextResponse`, or a bare `Response` | | `async def` | runs on the event loop | | plain `def` | run in the thread pool, like a `def` path operation | | Returning a dict | not converted; the request fails with a 500 | The return-value rule surprises people because a path operation may return a dict. Exception handlers bypass FastAPI's response serialization entirely: Starlette calls the returned object as an ASGI application, so it has to be a real response. ## How a handler is chosen When an exception escapes a path operation or a dependency, Starlette's exception middleware, which FastAPI places inside your own middleware, looks for a handler: - For an `HTTPException`, it first checks handlers registered by **integer status code**, such as `@app.exception_handler(409)`. Integer keys match only `HTTPException` instances; a custom exception with a `status_code` attribute is not matched by them. - Otherwise it walks the raised class's **MRO** (`type(exc).__mro__`) and uses the first class that has a handler. A handler on `PaymentError` therefore catches `InsufficientFunds(PaymentError)`, and a more specific handler on `InsufficientFunds` would win because it comes earlier in the MRO. - If nothing matches, the exception keeps propagating. Two keys are treated differently: `Exception` and the integer `500`. FastAPI hands those to Starlette's **server-error middleware**, the outermost layer. A handler there builds the 500 response and the exception is then **re-raised**, so the ASGI server logs it and a `TestClient` with its default `raise_server_exceptions=True` raises it in the test. When the app runs with `debug=True`, that middleware sends a traceback page instead and skips the handler. ## Where it does not reach - **Your own middleware.** An exception raised inside `@app.middleware("http")` happens outside the exception middleware, so only the server-error layer sees it. - **A response that has already started.** If a streaming response fails after sending its first bytes, Starlette cannot replace it and raises `RuntimeError("Caught handled exception, but response already started.")`. The same lookup applies to exceptions raised inside **dependencies**, since they are solved within the same request handling: a `get_account` dependency that raises `InsufficientFunds` is mapped exactly like the path operation raising it. ## Testing the mapping The mapping is easy to pin down with an in-process `fastapi.testclient.TestClient`: 1. call an endpoint that raises the domain exception and assert the status (409) and the envelope's `code`; 2. raise a sibling subclass and assert the base-class handler answers; 3. assert that sensitive values, such as the shortfall, are absent from the body. ## Keeping internals out of the response The handler is now the only thing between the exception and the client, so it decides what leaks: - return a stable machine code (`INSUFFICIENT_FUNDS`) and a fixed message; - leave out balances, account numbers of other parties and `str(exc)` of lower-level errors; - log the details server-side, where the exception object is still available. ## Worked example The payments API declares a `PaymentError` base carrying a status and a code, and `InsufficientFunds` overrides them to 409 and `INSUFFICIENT_FUNDS`. One handler on the base serves every payment failure. A withdrawal of 500 from a balance of 100 receives `409 {"error": {"code": "INSUFFICIENT_FUNDS", "message": "The payment was refused"}}`, and the shortfall stays in the server's logs instead of the response.

  • In FastAPI, does @app.exception_handler(409) catch a custom exception whose status_code attribute is 409?
    No. Integer keys are looked up only when the raised exception is an `HTTPException`; other exceptions are matched by class along their MRO. A custom exception needs a handler registered on its class or a base class, whatever attributes it carries.
  • What happens when a FastAPI handler is registered on Exception?
    FastAPI passes it to Starlette's outermost server-error middleware instead of the normal exception middleware. It runs for any unhandled error and builds the 500, but the exception is re-raised afterwards so the server logs it, and with `debug=True` the traceback page is sent instead.

  • Returns a dict from the handler expecting FastAPI to serialize it
  • Registers the handler on an APIRouter instead of the app
  • Thinks only the exact exception class matches, not subclasses
  • Expects an integer status handler to catch any exception with that status
  • Copies str(exc) of a lower-level error into the response body