Error Handling Middleware¶
error_handling_middleware
¶
Middleware that catches unhandled exceptions and maps them to error responses.
ErrorHandlingMiddleware
¶
Bases: Middleware[RequestType, ResponseType]
Catches exceptions from downstream and maps them to responses.
Wraps the downstream handler in a try/except that catches
Exception (not BaseException — KeyboardInterrupt,
SystemExit and friends propagate). Caught exceptions are
converted to an ErrorViewModel via ErrorPresenter and then
mapped to a ResponseType by the required on_error callable.
An optional LoggerPort logs the exception at error level before
mapping.
Responsibilities
- Catch
Exceptionraised by the downstream handler. - Convert the exception to an
ErrorViewModel. - Map the view model to a
ResponseTypeviaon_error. - Optionally log the exception before mapping.
Non-Responsibilities
- Catch
BaseException(KeyboardInterrupt,SystemExit). - Define the error response shape — that lives in
on_error. - Handle errors from middleware upstream of this one.
Example
Source code in src/forging_blocks/presentation/builtin/error_handling_middleware.py
__init__(on_error: Callable[[ErrorViewModel], ResponseType], error_presenter: ErrorPresenter | None = None, logger: LoggerPort | None = None) -> None
¶
Wrap the pipeline with exception-to-response mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_error
|
Callable[[ErrorViewModel], ResponseType]
|
Required callable that maps an |
required |
error_presenter
|
ErrorPresenter | None
|
The |
None
|
logger
|
LoggerPort | None
|
An optional |
None
|
Source code in src/forging_blocks/presentation/builtin/error_handling_middleware.py
process(request: RequestType, next_handler: NextHandler[RequestType, ResponseType]) -> ResponseType
async
¶
Delegate to next_handler, catching Exception on failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
RequestType
|
The incoming request. |
required |
next_handler
|
NextHandler[RequestType, ResponseType]
|
The next callable in the pipeline chain. |
required |
Returns:
| Type | Description |
|---|---|
ResponseType
|
The downstream handler's response on success, or the result |
ResponseType
|
of |