Skip to content

ExceptionMiddleware

faststream.middlewares.ExceptionMiddleware #

ExceptionMiddleware(handlers=None, publish_handlers=None)
Source code in faststream/middlewares/exception.py
def __init__(
    self,
    handlers: dict[type[Exception], GeneralExceptionHandler] | None = None,
    publish_handlers: dict[type[Exception], PublishingExceptionHandler] | None = None,
) -> None:
    self._handlers: CastedHandlers = [
        (IgnoredException, ignore_handler),
        *(
            (
                exc_type,
                apply_types(
                    cast("Callable[..., Awaitable[None]]", to_async(handler)),
                    serializer_cls=None,
                ),
            )
            for exc_type, handler in (handlers or {}).items()
        ),
    ]

    self._publish_handlers: CastedPublishingHandlers = [
        (IgnoredException, ignore_handler),
        *(
            (exc_type, apply_types(to_async(handler), serializer_cls=None))
            for exc_type, handler in (publish_handlers or {}).items()
        ),
    ]

add_handler #

add_handler(
    exc: type[Exception], publish: Literal[False] = False
) -> Callable[
    [GeneralExceptionHandler], GeneralExceptionHandler
]
add_handler(
    exc: type[Exception], publish: Literal[True] = ...
) -> Callable[
    [PublishingExceptionHandler], PublishingExceptionHandler
]
add_handler(exc, publish=False)
Source code in faststream/middlewares/exception.py
def add_handler(
    self,
    exc: type[Exception],
    publish: bool = False,
) -> (
    Callable[[GeneralExceptionHandler], GeneralExceptionHandler]
    | Callable[[PublishingExceptionHandler], PublishingExceptionHandler]
):
    if publish:

        def pub_wrapper(
            func: PublishingExceptionHandler,
        ) -> PublishingExceptionHandler:
            self._publish_handlers.append(
                (
                    exc,
                    apply_types(to_async(func), serializer_cls=None),
                ),
            )
            return func

        return pub_wrapper

    def default_wrapper(
        func: GeneralExceptionHandler,
    ) -> GeneralExceptionHandler:
        self._handlers.append(
            (
                exc,
                apply_types(to_async(func), serializer_cls=None),
            ),
        )
        return func

    return default_wrapper