fastapi/fastapi
Exceptions
Purpose
Two files cover error handling end to end:
fastapi/exceptions.pydefines the exception classes and theEndpointContexttyped dict.fastapi/exception_handlers.pyprovides the default async handlers thatFastAPIregisters in its constructor.
Class hierarchy
StarletteHTTPException
└── HTTPException # fastapi/exceptions.py
StarletteWebSocketException
└── WebSocketException # fastapi/exceptions.py
RuntimeError
└── FastAPIError
├── DependencyScopeError
└── PydanticV1NotSupportedError
UserWarning
└── FastAPIDeprecationWarning
Exception
└── ValidationException
├── RequestValidationError
├── WebSocketRequestValidationError
└── ResponseValidationErrorKey abstractions
| Class | Purpose |
|---|---|
HTTPException(status_code, detail, headers) |
Raise from your code to send an HTTP error response. Subclass of Starlette's class — kept thin so it can be isinstance-checked against either. |
WebSocketException(code, reason) |
Raise to close a WebSocket with the given RFC 6455 code. |
FastAPIError |
Generic framework misuse. |
DependencyScopeError |
A function-scoped dependency depends on a request-scoped dependency. Detected during dependant build. |
PydanticV1NotSupportedError |
Raised at model-creation time when a Pydantic v1 model is supplied. |
FastAPIDeprecationWarning |
Subclass of UserWarning (Python's defaults filter DeprecationWarning for libraries — see the docstring for the rationale). |
EndpointContext |
TypedDict(total=False) carrying function, path, file, line. Populated by _extract_endpoint_context (fastapi/routing.py) and attached to validation errors so messages can name the endpoint. |
ValidationException |
Internal base for the three validation errors. Holds a sequence of error dicts and an optional endpoint_ctx. The __str__ includes function, file, line, and path when available. |
RequestValidationError(errors, body, endpoint_ctx) |
Raised by solve_dependencies when request data fails validation. Carries the parsed body for diagnostics. |
WebSocketRequestValidationError(errors, endpoint_ctx) |
The WebSocket counterpart. |
ResponseValidationError(errors, body, endpoint_ctx) |
Raised by serialize_response when the function's return value fails the response_model. |
RequestErrorModel, WebSocketErrorModel |
Pydantic root models created with create_model("Request") / create_model("WebSocket") — used to namespace error locations. |
Default handlers
Registered in FastAPI.__init__ via the inherited Starlette exception_handlers mapping:
| Exception | Handler | Behaviour |
|---|---|---|
HTTPException |
http_exception_handler |
Returns {"detail": exc.detail} as JSON if a body is allowed for the status code, else an empty Response with the status. Forwards headers from the exception. |
RequestValidationError |
request_validation_exception_handler |
Returns 422 with {"detail": jsonable_encoder(exc.errors())}. |
WebSocketRequestValidationError |
websocket_request_validation_exception_handler |
Closes the WebSocket with WS_1008_POLICY_VIOLATION and the reason set to the JSON-encoded errors. |
is_body_allowed_for_status_code (fastapi/utils.py) returns False for 204, 205, 304 and any 1xx — those statuses must not carry a body, so http_exception_handler returns an empty Response for them.
Customising
- Replace handlers via
app.add_exception_handler(HTTPException, my_handler)or@app.exception_handler(HTTPException). The handler can be sync or async. - For per-route response shapes, use the
responses=parameter on the route decorator (which only affects OpenAPI), or raise a more specific exception that you have a handler for. endpoint_ctxis opt-in via the routing layer — handlers receive plainExceptionobjects and can decide whether to surface the context.
Integration points
- Up to user code —
HTTPException,WebSocketException, and the default handler functions are public API. - Across to routing —
_extract_endpoint_contextpopulatesEndpointContext; the routing layer raisesRequestValidationErrorandResponseValidationErrorwith that context attached. - Across to dependency resolver —
DependencyScopeErroris raised duringget_dependantwhen scope rules are violated. - Down to Starlette —
HTTPException/WebSocketExceptionsubclass Starlette's so existing Starlette code that catches the parent class still works.
Entry points for modification
- New error class: add to
fastapi/exceptions.py, raise from where the condition arises, register a default handler inFastAPI.__init__if you want a default behaviour. - New context fields: extend
EndpointContextand_extract_endpoint_context. UpdateValidationException.__str__to render them. - Changing the validation-error wire format: edit
request_validation_exception_handlerand the matchingvalidation_error_definitioninfastapi/openapi/utils.pyso the schema reflects the runtime shape.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.
Previous
Encoders
Next
Middleware