Factory.ai

Open-Source Wikis

/

FastAPI

/

Systems

/

Exceptions

fastapi/fastapi

Exceptions

Purpose

Two files cover error handling end to end:

  • fastapi/exceptions.py defines the exception classes and the EndpointContext typed dict.
  • fastapi/exception_handlers.py provides the default async handlers that FastAPI registers 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
    └── ResponseValidationError

Key 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_ctx is opt-in via the routing layer — handlers receive plain Exception objects and can decide whether to surface the context.

Integration points

  • Up to user codeHTTPException, WebSocketException, and the default handler functions are public API.
  • Across to routing_extract_endpoint_context populates EndpointContext; the routing layer raises RequestValidationError and ResponseValidationError with that context attached.
  • Across to dependency resolverDependencyScopeError is raised during get_dependant when scope rules are violated.
  • Down to StarletteHTTPException/WebSocketException subclass 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 in FastAPI.__init__ if you want a default behaviour.
  • New context fields: extend EndpointContext and _extract_endpoint_context. Update ValidationException.__str__ to render them.
  • Changing the validation-error wire format: edit request_validation_exception_handler and the matching validation_error_definition in fastapi/openapi/utils.py so 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.

Exceptions – FastAPI wiki | Factory