Coverage for faststream/middlewares/exception.py: 97%
46 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1from collections.abc import Awaitable, Callable
2from contextlib import nullcontext
3from typing import (
4 TYPE_CHECKING,
5 Any,
6 Literal,
7 NoReturn,
8 Optional,
9 TypeAlias,
10 cast,
11 overload,
12)
14from faststream._internal.middlewares import BaseMiddleware
15from faststream._internal.utils import apply_types
16from faststream._internal.utils.functions import to_async
17from faststream.exceptions import IgnoredException
19if TYPE_CHECKING:
20 from contextlib import AbstractContextManager
21 from types import TracebackType
23 from faststream._internal.basic_types import AsyncFuncAny
24 from faststream._internal.context.repository import ContextRepo
25 from faststream.message import StreamMessage
28GeneralExceptionHandler: TypeAlias = Callable[..., None] | Callable[..., Awaitable[None]]
29PublishingExceptionHandler: TypeAlias = Callable[..., Any]
31CastedGeneralExceptionHandler: TypeAlias = Callable[..., Awaitable[None]]
32CastedPublishingExceptionHandler: TypeAlias = Callable[..., Awaitable[Any]]
33CastedHandlers: TypeAlias = dict[
34 type[Exception],
35 CastedGeneralExceptionHandler,
36]
37CastedPublishingHandlers: TypeAlias = dict[
38 type[Exception],
39 CastedPublishingExceptionHandler,
40]
43class ExceptionMiddleware:
44 __slots__ = ("_handlers", "_publish_handlers")
46 _handlers: CastedHandlers
47 _publish_handlers: CastedPublishingHandlers
49 def __init__(
50 self,
51 handlers: dict[type[Exception], GeneralExceptionHandler] | None = None,
52 publish_handlers: dict[type[Exception], PublishingExceptionHandler] | None = None,
53 ) -> None:
54 self._handlers: CastedHandlers = {
55 IgnoredException: ignore_handler,
56 **{
57 exc_type: apply_types(
58 cast("Callable[..., Awaitable[None]]", to_async(handler)),
59 serializer_cls=None,
60 )
61 for exc_type, handler in (handlers or {}).items()
62 },
63 }
65 self._publish_handlers: CastedPublishingHandlers = {
66 IgnoredException: ignore_handler,
67 **{
68 exc_type: apply_types(to_async(handler), serializer_cls=None)
69 for exc_type, handler in (publish_handlers or {}).items()
70 },
71 }
73 @overload
74 def add_handler(
75 self,
76 exc: type[Exception],
77 publish: Literal[False] = False,
78 ) -> Callable[[GeneralExceptionHandler], GeneralExceptionHandler]: ...
80 @overload
81 def add_handler(
82 self,
83 exc: type[Exception],
84 publish: Literal[True] = ...,
85 ) -> Callable[[PublishingExceptionHandler], PublishingExceptionHandler]: ...
87 def add_handler(
88 self,
89 exc: type[Exception],
90 publish: bool = False,
91 ) -> (
92 Callable[[GeneralExceptionHandler], GeneralExceptionHandler]
93 | Callable[[PublishingExceptionHandler], PublishingExceptionHandler]
94 ):
95 if publish:
97 def pub_wrapper(
98 func: PublishingExceptionHandler,
99 ) -> PublishingExceptionHandler:
100 self._publish_handlers[exc] = apply_types(
101 to_async(func),
102 serializer_cls=None,
103 )
104 return func
106 return pub_wrapper
108 def default_wrapper(
109 func: GeneralExceptionHandler,
110 ) -> GeneralExceptionHandler:
111 self._handlers[exc] = apply_types(
112 to_async(func),
113 serializer_cls=None,
114 )
115 return func
117 return default_wrapper
119 def __call__(
120 self,
121 msg: Any | None,
122 /,
123 *,
124 context: "ContextRepo",
125 ) -> "_BaseExceptionMiddleware":
126 """Real middleware runtime constructor."""
127 return _BaseExceptionMiddleware(
128 handlers=self._handlers,
129 publish_handlers=self._publish_handlers,
130 context=context,
131 msg=msg,
132 )
135class _BaseExceptionMiddleware(BaseMiddleware):
136 __slots__ = ("_handlers", "_publish_handlers")
138 def __init__(
139 self,
140 *,
141 handlers: CastedHandlers,
142 publish_handlers: CastedPublishingHandlers,
143 context: "ContextRepo",
144 msg: Any | None,
145 ) -> None:
146 super().__init__(msg, context=context)
147 self._handlers = handlers
148 self._publish_handlers = publish_handlers
150 async def consume_scope(
151 self,
152 call_next: "AsyncFuncAny",
153 msg: "StreamMessage[Any]",
154 ) -> Any:
155 try:
156 return await call_next(msg)
158 except Exception as exc:
159 for cls in type(exc).__mro__:
160 if cls in self._publish_handlers:
161 return await self._publish_handlers[cls](exc, context__=self.context)
163 raise
165 async def after_processed(
166 self,
167 exc_type: type[BaseException] | None = None,
168 exc_val: BaseException | None = None,
169 exc_tb: Optional["TracebackType"] = None,
170 ) -> bool | None:
171 if exc_type:
172 for cls in exc_type.__mro__:
173 if cls in self._handlers:
174 handler = self._handlers[cls]
175 # TODO: remove it after context will be moved to middleware
176 # In case parser/decoder error occurred
177 scope: AbstractContextManager[Any]
178 if not self.context.get_local("message"): 178 ↛ 179line 178 didn't jump to line 179 because the condition on line 178 was never true
179 scope = self.context.scope("message", self.msg)
180 else:
181 scope = nullcontext()
183 with scope:
184 await handler(exc_val, context__=self.context)
186 return True
188 return False
190 return None
193async def ignore_handler(
194 exception: IgnoredException,
195 **kwargs: Any, # suppress context
196) -> NoReturn:
197 raise exception