Exceptions & Error Handling
Relevant source files
The following files were used as context for generating this wiki page:
The Exception and Error Handling system in Starlette provides a robust framework for managing both expected application errors (via HTTP and WebSocket exceptions) and unexpected server-side failures. It utilizes a layered middleware approach to ensure that exceptions occurring during the request-response cycle are caught, processed, and transformed into appropriate responses for the client.
The architecture relies on two primary middleware components: the ServerErrorMiddleware, which acts as the outermost layer to catch all unhandled exceptions, and the ExceptionMiddleware, which resides closer to the application logic to handle specific status codes or exception classes defined by the developer.
Sources: starlette/applications.py:53-62, starlette/middleware/exceptions.py:16-25
Core Exception Classes
Starlette defines specialized exception classes to represent common web-related error states. These classes allow developers to raise errors with specific metadata that the middleware can later interpret.
HTTPException
Used to represent an error that should result in an HTTP response. It encapsulates a status code, an optional detail message, and optional headers. If no detail is provided, it defaults to the standard HTTP status phrase.
Sources: starlette/exceptions.py:7-22
WebSocketException
Used for errors within WebSocket connections. It includes a numeric close code and a string reason.
Sources: starlette/exceptions.py:25-34
| Class | Attributes | Purpose |
|---|---|---|
HTTPException | status_code, detail, headers | Triggers specific HTTP error responses. |
WebSocketException | code, reason | Triggers WebSocket closure with specific codes. |
Middleware Architecture
Starlette applications automatically configure a middleware stack that handles exceptions at different levels of the ASGI scope.
This diagram shows the flow of a request through the exception handling layers.
Sources: starlette/applications.py:74-82
ServerErrorMiddleware
The ServerErrorMiddleware is the outermost layer of the application. Its primary responsibility is to catch any exception that propagates out of the entire middleware stack and the application itself.
- Debug Mode: If
debug=True, it generates an interactive HTML or plain text traceback response containing detailed information about the error, including code snippets and local variables. - Production Mode: If
debug=False, it uses a providedhandleror returns a default "Internal Server Error" plain text response with a 500 status code. - Exception Re-raising: This middleware always re-raises the caught exception after sending the response, allowing the ASGI server to log the error.
Sources: starlette/middleware/errors.py:94-153, starlette/middleware/errors.py:210-222
ExceptionMiddleware
The ExceptionMiddleware is positioned as the innermost middleware. it handles HTTPException, WebSocketException, and any custom exception handlers mapped to specific status codes or exception types.
- Status Handlers: Mappings of integer status codes (e.g., 404) to handler functions.
- Exception Handlers: Mappings of Exception classes to handler functions.
- Handler Execution: It uses
wrap_app_handling_exceptionsto execute the app logic and catch exceptions, then looks up the appropriate handler.
Sources: starlette/middleware/exceptions.py:16-35, starlette/middleware/exceptions.py:58-66
Exception Handler Logic
Exception handlers in Starlette can be standard functions or asynchronous functions. They typically receive a Request (or WebSocket) and the Exception instance, returning a Response.
This sequence diagram illustrates how ExceptionMiddleware routes an exception to a specific handler.
Sources: starlette/middleware/exceptions.py:37-56, starlette/middleware/errors.py:133-144
Handling Rules
- Response Started Check: If an exception occurs after the HTTP response has already started (i.e.,
http.response.starthas been sent), Starlette cannot trigger a new error response and will raise aRuntimeError. - WebSocket Exceptions: For
WebSocketException, the middleware automatically closes the connection using the provided code and reason. - Internal Server Error (500): Handlers for status code 500 or the base
Exceptionclass are treated as the global error handler and passed to theServerErrorMiddleware.
Sources: starlette/middleware/exceptions.py:68-71, starlette/middleware/errors.py:146-150, starlette/applications.py:69-73
Summary of Components
| Component | File Path | Description |
|---|---|---|
ServerErrorMiddleware | starlette/middleware/errors.py | Outer layer; handles 500 errors and debug tracebacks. |
ExceptionMiddleware | starlette/middleware/exceptions.py | Inner layer; dispatches specific exceptions to handlers. |
HTTPException | starlette/exceptions.py | Standard exception for HTTP errors. |
WebSocketException | starlette/exceptions.py | Standard exception for WebSocket closure. |
build_middleware_stack | starlette/applications.py | Logic that assembles the layered handling architecture. |
The Starlette error handling system ensures that application failures are gracefully managed, providing developers with powerful debugging tools during development and reliable error reporting in production environments.
Sources: starlette/applications.py:64-83, starlette/middleware/errors.py:18-91