### Quickstart: dispatch a command with CommandBus Source: https://github.com/100nm/python-cq/blob/prod/docs/index.md Quickstart example showing how to define a command, register a handler with @command_handler, and dispatch it via the CommandBus. The decorator registers the handler against the type of its first handle parameter. The bus is resolved by the DI container and dispatched to that handler. ```python import asyncio from cq import CommandBus, command_handler from dataclasses import dataclass from injection import inject @dataclass class CreateUserCommand: name: str email: str @command_handler class CreateUserHandler: async def handle(self, command: CreateUserCommand) -> int: # ... persist the user, return its id return 42 @inject async def main(bus: CommandBus[int]) -> None: command = CreateUserCommand(name="Ada", email="ada@example.com") user_id = await bus.dispatch(command) print(f"Created user {user_id}") asyncio.run(main()) ``` -------------------------------- ### Middleware execution order example Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md Shows the execution order of middlewares: the first argument is the outermost layer, starting first and finishing last. ```python bus.add_middlewares(outer, inner) # outer -> inner -> handler -> inner -> outer ``` -------------------------------- ### Install python-cq with injection extra Source: https://github.com/100nm/python-cq/blob/prod/README.md Install python-cq with the injection extra to use python-injection as the default DI backend. Requires Python 3.12 or higher. ```bash pip install "python-cq[injection]" ``` -------------------------------- ### Install python-cq without DI Source: https://github.com/100nm/python-cq/blob/prod/docs/index.md Install python-cq without dependency injection. You will need to implement a DIAdapter. ```bash pip install python-cq ``` -------------------------------- ### Dispatch a query with QueryBus Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/dispatching.md Dispatch a query to its single registered handler and get the returned value. The bus is typed with the return type, and the example assumes the bus has already been resolved from the DI container. ```python from cq import QueryBus bus: QueryBus[User] = ... query = GetUserByIdQuery(user_id=42) user = await bus.dispatch(query) ``` -------------------------------- ### Dispatch a command with CommandBus Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/dispatching.md Dispatch a command to its single registered handler and get the returned value. The bus is typed with the return type, and the example assumes the bus has already been resolved from the DI container. ```python from cq import CommandBus bus: CommandBus[int] = ... command = CreateUserCommand(name="Ada", email="ada@example.com") user_id = await bus.dispatch(command) ``` -------------------------------- ### Define a listener for logging messages Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md Example listener that logs each message. Listeners are callables that receive the message and return nothing; they are scheduled in an anyio task group and run concurrently. On CommandBus and QueryBus, all listeners must finish before the handler runs; on EventBus, listeners and handlers share the same task group. ```python async def log_listener(message): print(f"Received: {message}") ``` -------------------------------- ### Drain a queue with Pump Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/queues.md Basic usage of Pump to connect a MemoryQueue to a CommandBus dispatcher. The draining context starts a background task that consumes the queue and forwards messages to the dispatcher; on exit the task group is cancelled by default, stopping the pump immediately even if messages are in flight. ```python from cq import Command, CommandBus, MemoryQueue, Pump from typing import Any command_bus: CommandBus[Any] = ... queue: MemoryQueue[Command] = MemoryQueue() async with Pump(queue, command_bus).draining(): # ... await queue.send(command) ``` -------------------------------- ### Add multiple events in one call Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Adds multiple events in a single call to events.add. This is a short example showing that RelatedEvents.add accepts multiple event arguments. ```python self.events.add(event_1, event_2) ``` -------------------------------- ### Polymorphic dispatch with @event_handler Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Shows polymorphic dispatch: a handler registered for a base class (or Protocol or generic alias) receives any subclass. This example registers an event handler for DomainEvent, which will also receive UserCreatedEvent and other subclasses. Resolution uses the message's MRO and supports type aliases. ```python class DomainEvent: ... class UserCreatedEvent(DomainEvent): user_id: int @event_handler class AuditLogger: async def handle(self, event: DomainEvent): # Receives UserCreatedEvent and any other DomainEvent subclass. ... ``` -------------------------------- ### Define a pipeline with steps using ContextCommandPipeline Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Shows how to create a pipeline with the default Router instance and define steps that receive the previous result and return the next command. Steps can assign instance attributes that are visible in later steps. ```python from cq import ContextCommandPipeline class PaymentContext: transaction_id: int pipeline: ContextCommandPipeline[ValidateCartCommand] = ContextCommandPipeline() @pipeline.step def _(self, result: CartValidatedResult) -> CreateTransactionCommand: return CreateTransactionCommand(cart_id=result.cart_id, amount=result.total) @pipeline.step def _(self, result: TransactionCreatedResult) -> NotifyMerchantCommand: self.transaction_id = result.transaction_id return NotifyMerchantCommand(transaction_id=result.transaction_id) @pipeline.step def _(self, result: MerchantNotifiedResult): ... ``` -------------------------------- ### Run a pipeline implicitly with Context.pipeline Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Shows how to run a pipeline implicitly by calling Context.pipeline(initial_command). A fresh Context instance is created, every step runs against it, and the populated context is returned. Attributes set in one run do not leak into the next. ```python async def process_payment(cart_id: int) -> int: command = ValidateCartCommand(cart_id=cart_id) context = await PaymentContext.pipeline(command) return context.transaction_id ``` -------------------------------- ### Seed context with base values using a run classmethod Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Shows how to seed a context with base values by instantiating the context yourself and calling pipeline on the instance. The same object is returned at the end, mutated by every step that ran. The recommended pattern is to centralize both calls behind a run classmethod. ```python from cq import ContextCommandPipeline from typing import ClassVar, Self from uuid import UUID class LinkOAuthAccountContext: pipeline: ClassVar[ContextCommandPipeline[VerifyIDTokenCommand]] = ( ContextCommandPipeline() ) def __init__(self, user_id: UUID, provider: OAuthProvider) -> None: self.user_id = user_id self.provider = provider @pipeline.step def _(self, user: OAuthUser) -> LinkOAuthAccountCommand: return LinkOAuthAccountCommand( user_id=self.user_id, provider=self.provider, provider_user_id=user.id, email=user.email, ) @classmethod async def run(cls, user_id: UUID, command: VerifyIDTokenCommand) -> Self: return await cls(user_id, command.provider).pipeline(command) ``` -------------------------------- ### Create custom Router with DI adapter Source: https://github.com/100nm/python-cq/blob/prod/docs/di.md Creates a custom Router instance with a custom DI adapter and registers default handlers and bus factories. Use this to wire the library against a custom DIAdapter instead of the default module-level decorators and bus factories. ```python from cq import Router router = Router(my_di_adapter).register_defaults() command_handler = router.command_handler event_handler = router.event_handler query_handler = router.query_handler new_command_bus = router.new_command_bus new_event_bus = router.new_event_bus new_query_bus = router.new_query_bus ``` -------------------------------- ### Add static steps to a pipeline Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Shows how to add static steps that are dispatched as-is each time the pipeline runs, using add_static_step for commands and add_static_query_step for queries. Static steps and decorated steps are interleaved in declaration order. ```python class WarmCachePipeline: pipeline: ContextCommandPipeline[StartCommand] = ContextCommandPipeline() pipeline.add_static_step(LoadConfigCommand()) pipeline.add_static_query_step(GetActiveUsersQuery()) @pipeline.step def _(self, users: list[User]) -> WarmCacheCommand: return WarmCacheCommand(user_ids=[u.id for u in users]) ``` -------------------------------- ### Adding middlewares in sequence Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md Demonstrates that each subsequent call wraps the existing middlewares, so the last added ends up outermost. ```python bus.add_middlewares(a, b) # a -> b -> handler bus.add_middlewares(c) # c -> a -> b -> handler ``` -------------------------------- ### Build command pipeline from custom Router Source: https://github.com/100nm/python-cq/blob/prod/docs/di.md Builds a command pipeline from a custom Router instance so it dispatches through the right buses. If using the default Router, ContextCommandPipeline() with no argument is enough. ```python from cq import ContextCommandPipeline class PaymentContext: pipeline: ContextCommandPipeline[ValidateCartCommand] = router.command_pipeline() ``` -------------------------------- ### Configure a CommandBus with listeners and middlewares Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md Factory pattern for building a configured CommandBus and registering it with the DI container. Requires the [injection] extra; if using a different DI framework, register the factory with your own container instead of @injectable. The same pattern applies to QueryBus and EventBus with new_query_bus() and new_event_bus(). ```python from cq import CommandBus, new_command_bus from injection import injectable async def listener(message): ... async def middleware(message): # runs before the handler result = yield # runs after the handler @injectable def command_bus_factory() -> CommandBus: bus = new_command_bus() bus.add_listeners(listener) bus.add_middlewares(middleware) return bus ``` -------------------------------- ### Dispatch a query with @pipeline.query_step Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Shows how to use @pipeline.query_step to dispatch a message through the QueryBus instead of the CommandBus. ```python @pipeline.query_step def _(self, result: TransactionCreatedResult) -> GetMerchantByIdQuery: return GetMerchantByIdQuery(merchant_id=result.merchant_id) ``` -------------------------------- ### Implement DIAdapter protocol Source: https://github.com/100nm/python-cq/blob/prod/docs/di.md Implements the DIAdapter protocol with the required lazy and wire methods, plus optional command_scope and register_defaults. The reference implementation for python-injection is in cq.ext.injection.InjectionAdapter. ```python from collections.abc import Awaitable, Callable from cq import Router, Command, DIAdapter, CommandBus, EventBus, Middleware, QueryBus from typing import Any, Concatenate class MyDIAdapter(DIAdapter): def command_scope(self) -> Middleware[Concatenate[Command, ...], Any] | None: """ Return a middleware that wraps each command dispatch. It must manage the lifecycle of a `RelatedEvents` instance and make it resolvable for as long as the dispatch lasts, so that command handlers can inject it. If you already have an async context manager for the scope, wrap it with `cq.middlewares.contextlib.AsyncContextManagerMiddleware` instead of writing the middleware by hand. Optional: the default implementation returns `None`, meaning no middleware wraps the dispatch. Command handlers then have no `RelatedEvents` to inject. """ ... def lazy[T](self, tp: type[T]) -> Callable[[], Awaitable[T]]: """ Return a callable that, when called and awaited, resolves `tp` from the container. Used to wire up bus references lazily so that buses configured later in the import graph are still picked up. """ ... def register_defaults( self, command_bus: Callable[..., CommandBus[Any]], event_bus: Callable[..., EventBus], query_bus: Callable[..., QueryBus[Any]], ) -> None: """ Register the bus factories with the container so that handlers can declare `CommandBus`, `EventBus`, or `QueryBus` as dependencies. Optional: the default implementation is a no-op, which is fine if your container does not need explicit registration. """ ... def wire[T](self, tp: type[T]) -> Callable[..., Awaitable[T]]: """ Return an async factory that instantiates `tp` with injected dependencies. Used internally to build handler instances. """ ... router = Router(MyDIAdapter()).register_defaults() ``` -------------------------------- ### Create and send to a MemoryQueue Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/queues.md Creates an in-process MemoryQueue with a buffer of 100 messages and sends a command. The default maxsize=0 means no buffering, so send blocks until a consumer takes the message; pass maxsize=math.inf for an unbounded buffer. MemoryQueue is not thread-safe and must be used on the event loop that created it. ```python from cq import Command, MemoryQueue queue: MemoryQueue[Command] = MemoryQueue(maxsize=100) await queue.send(command) ``` -------------------------------- ### Add middlewares to a pipeline with add_middlewares Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Wrap a pipeline with middlewares using add_middlewares. Middlewares wrap the whole pipeline execution, not each individual step. Individual command middlewares on the underlying CommandBus still apply to every command dispatched by the pipeline. ```python class PaymentContext: pipeline = ContextCommandPipeline().add_middlewares( timing_middleware, retry_middleware ) # ... ``` -------------------------------- ### Add RetryMiddleware to command bus Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md Configures a command bus with RetryMiddleware to retry on TimeoutError up to 3 attempts with a 0.5 second delay. The retry parameter is the total number of attempts, delay defaults to 0, and exceptions defaults to (Exception,). If all attempts fail, the last exception is re-raised. ```python from cq import new_command_bus from cq.middlewares.retry import RetryMiddleware bus = new_command_bus() bus.add_middlewares(RetryMiddleware(retry=3, delay=0.5, exceptions=(TimeoutError,))) ``` -------------------------------- ### Class-based listeners and middlewares with __call__ Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md Defines three class-based listeners/middlewares using dataclasses and async __call__ methods. LogListener logs messages, TimingMiddleware uses a generator-style middleware with yield, and ClassicTimingMiddleware uses the call_next pattern. These classes can be built through a DI container for constructor injection. ```python from dataclasses import dataclass @dataclass class LogListener: logger: Logger async def __call__(self, message): self.logger.info(f"Received: {message}") @dataclass class TimingMiddleware: metrics: MetricsService async def __call__(self, message): start = time.time() yield await self.metrics.record(time.time() - start) @dataclass class ClassicTimingMiddleware: metrics: MetricsService async def __call__(self, call_next, message): start = time.time() result = await call_next(message) await self.metrics.record(time.time() - start) return result ``` -------------------------------- ### Classic timing middleware with call_next Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md A classic middleware that takes call_next as its first argument and can read or substitute the handler's return value. ```python import time async def timing_middleware(call_next, message): start = time.time() result = await call_next(message) print(f"Execution time: {time.time() - start}s") return result ``` -------------------------------- ### Stop a pipeline conditionally by returning None Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Shows a step that returns None to stop the pipeline immediately, which is useful for terminal steps or conditional aborts. ```python @pipeline.step def _(self, result: ValidationResult): if result.is_valid: return PersistCommand(...) return None # stop here, skip the rest of the pipeline ``` -------------------------------- ### Add CaptureExceptionMiddleware with async report callback Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md Adds CaptureExceptionMiddleware to a command bus with an async report callback that captures exceptions via sentry_sdk. The reraise=True parameter re-raises the exception after the callback; defaults to False (swallowing). The on_error callback is for side effects only and must not raise. ```python from cq import new_command_bus from cq.middlewares.exc import CaptureExceptionMiddleware async def report(exception, message): sentry_sdk.capture_exception(exception) bus = new_command_bus() bus.add_middlewares(CaptureExceptionMiddleware(report, reraise=True)) ``` -------------------------------- ### Concurrent consumption with draining(concurrency=4) Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/queues.md Concurrent consumption with concurrency=N spawns N drain tasks against the same Consumer. Requires the Consumer implementation to be safe for concurrent iteration (MemoryQueue is, since it wraps an anyio memory stream). Ordering is no longer guaranteed when concurrency > 1. ```python async with Pump(queue, command_bus).draining(concurrency=4): # ... ``` -------------------------------- ### Add pump middleware with add_middlewares Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/queues.md Add a pump-level middleware stack via add_middlewares, using the same syntax and conventions as a bus. Pump-level middlewares wrap the consumption cycle, while bus-level middlewares still apply to every message dispatched. Note that fail_silently=True also swallows exceptions raised from a pump middleware. ```python async def sentry_middleware(message): try: yield except Exception as exc: sentry_sdk.capture_exception(exc) pump = Pump(queue, command_bus).add_middlewares(sentry_middleware) ``` -------------------------------- ### Dispatching messages sequentially with dispatch_sequentially Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Use dispatch_sequentially to drive the system into a known state by dispatching multiple commands in order. The dispatcher waits for each command to complete before proceeding, and exceptions propagate immediately. ```python from cq import CommandBus, dispatch_sequentially bus: CommandBus[Any] = ... account_id = 42 _, _, subscription = await dispatch_sequentially( bus, CreateAccountCommand(account_id=account_id, email="ada@example.com"), SubscribeToPlanCommand(account_id=account_id, plan="pro"), SuspendSubscriptionCommand(account_id=account_id, reason="payment_failed"), ) ``` -------------------------------- ### Yield-based timing middleware Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/configuring.md A middleware using the yield form. It runs before and after the handler, but cannot replace the handler's return value. ```python import time async def timing_middleware(message): start = time.time() yield print(f"Execution time: {time.time() - start}s") ``` -------------------------------- ### Define a command handler with @command_handler Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Defines a command handler that processes a CreateUserCommand and returns the new user's ID. The handler is a NamedTuple with a repository dependency and uses the @command_handler decorator. ```python from cq import command_handler from dataclasses import dataclass from typing import NamedTuple @dataclass class CreateUserCommand: name: str email: str @command_handler class CreateUserHandler(NamedTuple): repository: UserRepository async def handle(self, command: CreateUserCommand) -> int: user = await self.repository.create(command.name, command.email) return user.id ``` -------------------------------- ### Dispatch an event with EventBus Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/dispatching.md Dispatch an event to all registered handlers. The bus returns nothing, and handlers run concurrently inside a single anyio task group. If any handler raises (and is not declared with fail_silently=True), the exception is propagated, possibly as an ExceptionGroup. ```python from cq import EventBus bus: EventBus = ... event = UserCreatedEvent(user_id=42) await bus.dispatch(event) ``` -------------------------------- ### Event handlers with @event_handler Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Defines two event handlers for the same event, demonstrating that events can have multiple handlers. Both handlers run concurrently when the event is dispatched. ```python from cq import event_handler from dataclasses import dataclass from typing import NamedTuple @dataclass class UserCreatedEvent: user_id: int @event_handler class SendWelcomeEmailHandler(NamedTuple): email_service: EmailService async def handle(self, event: UserCreatedEvent): await self.email_service.send_welcome(event.user_id) @event_handler class TrackUserCreatedHandler(NamedTuple): analytics: AnalyticsService async def handle(self, event: UserCreatedEvent): await self.analytics.track("user_created", event.user_id) ``` -------------------------------- ### Use MemoryQueue.draining to pump and drain a queue Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/queues.md Use MemoryQueue.draining to combine a Pump with the queue's lifecycle. It opens a pump, yields the queue, and closes it on exit so the pump terminates gracefully without an explicit close call. The concurrency, fail_silently, and middlewares parameters are forwarded to the underlying Pump. ```python from cq import CommandBus, MemoryQueue from injection import inject from typing import Any @inject async def main(command_bus: CommandBus[Any]) -> None: async with MemoryQueue().draining(command_bus) as queue: # ... await queue.send(command_1) await queue.send(command_2) # Both commands have been dispatched here. ``` -------------------------------- ### Publish related events with RelatedEvents Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Shows how to inject a RelatedEvents object into a command handler to publish events during command execution. Events added via events.add are scheduled on a task group that lives for the duration of the command dispatch scope; they are dispatched concurrently and the command returns only after all scheduled events are handled. If an event handler raises, the exception propagates to the caller wrapped in two nested ExceptionGroups, catchable with except*. ```python from cq import RelatedEvents, command_handler @command_handler class CreateUserHandler(NamedTuple): repository: UserRepository events: RelatedEvents async def handle(self, command: CreateUserCommand): ... self.events.add(UserCreatedEvent(user_id=user.id)) ``` -------------------------------- ### Query handler with @query_handler Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Defines a query handler that reads state without side effects. The handler is a NamedTuple with a repository dependency and an async handle method that returns the user. ```python from cq import query_handler from dataclasses import dataclass from typing import NamedTuple @dataclass class GetUserByIdQuery: user_id: int @query_handler class GetUserByIdHandler(NamedTuple): repository: UserRepository async def handle(self, query: GetUserByIdQuery) -> User: return await self.repository.get(query.user_id) ``` -------------------------------- ### Define a message with dataclass Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Defines a message as a plain Python dataclass. No base class is required; the bus identifies handlers by the type annotation on the handler's handle method. ```python from dataclasses import dataclass @dataclass class CreateUserCommand: name: str email: str ``` -------------------------------- ### Graceful shutdown with draining(graceful=True) Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/queues.md Graceful shutdown of the pump. Passing graceful=True lets the pump finish draining already-queued messages before the context exits; the queue must be closed so the async iterator can terminate, otherwise the pump waits forever. ```python async with Pump(queue, command_bus).draining(graceful=True): # ... await queue.send(command_1) await queue.send(command_2) # ... await queue.close() ``` -------------------------------- ### Register a command handler with @command_handler Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Registers a handler for a command using the @command_handler decorator. The decorator inspects the annotation on the first parameter of handle to determine the message type. Constructor dependencies are resolved at runtime by the DI adapter. ```python from cq import command_handler @command_handler class CreateUserHandler: async def handle(self, command: CreateUserCommand): ... ``` -------------------------------- ### Handle the NotImplemented sentinel when no handler is registered Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/dispatching.md Check whether a dispatch returned the NotImplemented sentinel, which indicates no handler is registered for the message type. This is useful for optional messages, but means you should not assume a dispatch result is always meaningful. The same sentinel is returned when a handler declared with fail_silently=True raises. ```python result = await bus.dispatch(SomeQuery()) if result is NotImplemented: # No handler is registered for SomeQuery. ... ``` -------------------------------- ### Annotating dispatch_sequentially results Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/multiple_commands.md Annotate the target variable to ensure precise element types for the result tuple, as the variadic type parameter cannot be inferred automatically. ```python results: tuple[Account, Subscription, Subscription] = await dispatch_sequentially( bus, create_account, subscribe, suspend, ) ``` -------------------------------- ### Define a handler with NamedTuple Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Defines a handler as a NamedTuple for a concise, immutable declaration of its dependencies. The repository field is resolved by the DI container when the handler is instantiated. ```python from cq import command_handler from typing import NamedTuple @command_handler class CreateUserHandler(NamedTuple): repository: UserRepository async def handle(self, command: CreateUserCommand): ... ``` -------------------------------- ### Suppress dispatcher errors with fail_silently=True Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/queues.md Suppress dispatcher errors. By default an exception from the dispatcher stops the pump and propagates out of draining; with fail_silently=True individual failures are swallowed and the pump keeps consuming the rest of the queue. Use when each message is independent and a failed dispatch should not take down the whole consumer. ```python Pump(queue, command_bus, fail_silently=True) ``` -------------------------------- ### Event handler with fail_silently=True Source: https://github.com/100nm/python-cq/blob/prod/docs/guides/messages.md Suppresses exception propagation from an event handler by setting fail_silently=True. Middlewares still see the exception before it is suppressed. The same option is accepted on @command_handler and @query_handler, where dispatch returns the NotImplemented sentinel instead of propagating. ```python @event_handler(fail_silently=True) class TrackUserCreatedHandler(NamedTuple): analytics: AnalyticsService async def handle(self, event: UserCreatedEvent): # An exception here will be swallowed after middlewares run. ... ```