A FastAPI payments API registers its error envelope with @app.exception_handler(HTTPException), yet unknown paths still return {"detail": "Not Found"} and a broken response model returns plain-text 500. Why?
answer
- two HTTPException classes
- which class the router raises
- handler lookup walks the MRO
- ResponseValidationError has no default handler
basics
~20 sStarlette's router raises Starlette's HTTPException for 404 and 405, and a handler on FastAPI's subclass never matches its parent, so FastAPI's default answers. ResponseValidationError has no default handler and falls through to Starlette's plain-text 500.
solid answer
~40 s`fastapi.HTTPException` subclasses `starlette.exceptions.HTTPException`. Unmatched paths and wrong methods are raised by Starlette's router as the Starlette class, and handler lookup walks the raised class's MRO, which never contains FastAPI's subclass, so the default handler FastAPI registered on the Starlette class answers with `{"detail": "Not Found"}`. Registering the envelope on `starlette.exceptions.HTTPException` catches both, and forwarding `exc.headers` keeps `Allow` on 405s. A return value that fails `response_model` raises `ResponseValidationError`, which has no default handler; it reaches the server-error middleware and becomes `PlainTextResponse("Internal Server Error")`. A handler on `ResponseValidationError` logs it and returns the envelope's generic 500. Exceptions raised inside your own `@app.middleware("http")` sit outside the exception middleware and also end there.
code
python · 27 linesimport logging
from fastapi import FastAPI, Request
from fastapi.exceptions import ResponseValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
logger = logging.getLogger("payments")
app = FastAPI()
@app.exception_handler(StarletteHTTPException)
async def http_error_envelope(request: Request, exc: StarletteHTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"error": {"code": "HTTP_ERROR", "message": exc.detail}},
headers=exc.headers,
)
@app.exception_handler(ResponseValidationError)
async def response_contract_broken(request: Request, exc: ResponseValidationError):
logger.error("response failed its model: %s", exc)
return JSONResponse(
status_code=500,
content={"error": {"code": "INTERNAL", "message": "Internal error"}},
)go deeper
Recall that FastAPI's HTTPException is a subclass of Starlette's, and that unknown paths return 404 and wrong methods 405.
Explain MRO-based handler lookup and why ResponseValidationError, having no default handler, becomes a plain-text 500.
Diagnose every envelope gap: router errors, response validation, custom middleware, started streams; fix with the right registrations and prove each with a test.
Make the error envelope a tested contract, with one test per gap, so a new middleware or a FastAPI upgrade cannot quietly reintroduce a second error shape.
## Two classes with one name FastAPI ships its own `HTTPException` in `fastapi.exceptions`, a **subclass** of `starlette.exceptions.HTTPException`. The only difference is that FastAPI's accepts any JSON-able `detail`. When the app is created, FastAPI registers its default JSON handler on the **Starlette** class, along with handlers for `RequestValidationError` and `WebSocketRequestValidationError`. Your code raises FastAPI's class. Starlette's own machinery raises Starlette's class: - the router, when **no route matches** a path: `HTTPException(status_code=404)`; - the router, when the path matches but **the method does not**: `HTTPException(status_code=405)` with an `Allow` header; - Starlette's request parsing, for example when a **multipart form** cannot be parsed: a 400. ## Why the envelope misses routing errors When an exception reaches Starlette's exception middleware, it looks for a handler by walking `type(exc).__mro__`. For an exception raised as Starlette's class, that MRO is the Starlette class, then `Exception`, then the base classes; it never contains FastAPI's subclass. So: | Handler registered on | Your `raise HTTPException(404, ...)` | Router's 404 / 405 | |---|---|---| | `fastapi.HTTPException` | your envelope | FastAPI's default `{"detail": ...}` | | `starlette.exceptions.HTTPException` | your envelope | your envelope | Registering on the **Starlette** class fixes it, because FastAPI's subclass has the Starlette class in its MRO and is caught as well. This is the registration FastAPI's own docs recommend, so that errors raised by Starlette or its extensions reach the same handler. Pass `headers=exc.headers` to the `JSONResponse`: the 405 carries `Allow: GET`, and authentication errors raised as `HTTPException` carry `WWW-Authenticate`; dropping them breaks clients that rely on them. ## Why a broken response model is a plain-text 500 When a path operation returns data that does not validate against its `response_model` or return annotation, FastAPI raises `fastapi.exceptions.ResponseValidationError`. Its error locations start with `"response"`, and its string form includes the endpoint's file, line and function. It is a **server bug**, not a client error, so FastAPI registers **no** default handler for it. Like its request-side counterpart it exposes `errors()` and `body`, here the failing items and the value the path operation returned, which is material for logs. The exception therefore passes every handler and reaches Starlette's **server-error middleware**, the outermost layer, which: 1. sends `PlainTextResponse("Internal Server Error", status_code=500)`, or a traceback page when the app runs with `debug=True`; 2. **re-raises** the exception, so the ASGI server logs it with its details. Two fixes, with different behaviour: - **A handler on `ResponseValidationError`** runs inside the normal exception middleware. It can log `exc` (errors and endpoint context) and return the envelope's generic 500. The exception is handled and not re-raised. - **A handler on `Exception`** is moved to the server-error middleware by FastAPI. It shapes every unhandled 500, including this one, but the exception is still re-raised afterwards, and with `debug=True` the handler is skipped. Either way, the response body should say only that an internal error happened. The validation errors describe your code's return value, which may include data the client must not see. ## Other places the envelope does not reach - **Your own middleware.** FastAPI places the exception middleware *inside* user middleware, so an `HTTPException` raised in `@app.middleware("http")` is not handled by any registered handler and ends as a 500. - **Responses that already started streaming.** Once the first bytes are sent, a handler cannot replace the response. - **WebSocket routes**, whose validation errors close the socket rather than send a body. ## How to catch these in tests `fastapi.testclient.TestClient` has `raise_server_exceptions=True` by default, so a `ResponseValidationError` with no handler makes the test call raise instead of returning a 500. That is useful for finding the bug. To assert what clients actually receive, create the client with `raise_server_exceptions=False` and check the status and body. Add one test per gap: an unknown path, a wrong method, a malformed JSON body, a response that fails its model. ## Worked example After switching the handler to `starlette.exceptions.HTTPException` and adding one for `ResponseValidationError`, the payments API answers `GET /nope` with `404 {"error": {"code": "HTTP_ERROR", "message": "Not Found"}}`, `DELETE` on a GET-only route with a 405 carrying `Allow: GET`, and a handler returning `"lots"` for an integer balance with `500 {"error": {"code": "INTERNAL", "message": "Internal error"}}`, while the log holds the full validation error.
- In FastAPI, why does a handler on starlette.exceptions.HTTPException also catch HTTPExceptions raised by your own code?Your code raises `fastapi.HTTPException`, a subclass of the Starlette class. Handler lookup walks the raised exception's MRO, and the Starlette class appears in it, so the one handler serves both. The reverse is not true, which is the original bug.
- In a FastAPI test, why does a broken response model raise in TestClient instead of returning a 500?`TestClient` defaults to `raise_server_exceptions=True`, so an exception that reaches the server-error middleware is re-raised into the test. With no `ResponseValidationError` handler, that is what happens. Pass `raise_server_exceptions=False` to assert on the 500 a client would see.
- Registers the envelope handler only on fastapi.HTTPException
- Thinks a response_model mismatch returns a 422 to the client
- Drops exc.headers, losing Allow on 405 responses
- Returns ResponseValidationError details to the client
- Expects handlers to catch exceptions raised in custom middleware