Skip to content

feat: add subscriber and broker exception handlers - #3243

Draft
DMINQ wants to merge 12 commits into
ag2ai:mainfrom
DMINQ:feat/2945-exception-handlers
Draft

DMINQ wants to merge 12 commits into
ag2ai:mainfrom
DMINQ:feat/2945-exception-handlers

Conversation

@DMINQ

@DMINQ DMINQ commented Sep 26, 2026

Copy link
Copy Markdown

Description

Adds configurable exception handlers following the proposal in:
#3095 (comment)

The subscriber handler runs first. If it is absent or returns False,
the broker handler runs. Both synchronous and asynchronous handlers
are supported.

This draft currently exposes the API for Kafka and adds shared
dispatch logic to SubscriberUsecase.consume(). Unhandled exceptions
retain the existing consume() behavior. Middleware logging and
acknowledgement behavior remain unchanged.

Related to #2945. Background-task error handling is not implemented
yet, so this draft does not resolve the original Redis scenario.

Validation

  • Four automated test cases pass, covering handler precedence,
    fallback results and dispatch through consume().
  • The consume() test was verified to fail when the dispatch call
    was removed, and to pass with it restored.
  • Manually verified with a real Kafka broker: local handling,
    broker fallback, unhandled exceptions and continued processing.
  • Ruff lint and formatting checks passed for the changed files.
  • Mypy, Pyright and Pyrefly passed for the initial implementation.
  • Targeted Mypy checks passed after adding the consume() test.

Remaining work

  • Cover missing handlers and remaining sync/async combinations.
  • Integrate background-task error handling.
  • Expose the API across the remaining brokers.
  • Add documentation and runnable examples.
  • Complete the remaining project checks.

Type of change

  • New feature
  • This change requires a documentation update

Checklist

  • Self-reviewed the current changes.
  • Added automated tests for the implemented behavior.
  • Added documentation and tested examples.
  • Passed the full project lint checks (just lint).
  • Passed the relevant coverage checks.
  • Passed the full static analysis suite (just static-analysis).

@CLAassistant

CLAassistant commented Sep 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions Bot added the AioKafka Issues related to `faststream.kafka` module label Sep 26, 2026
@github-actions github-actions Bot added the Confluent Issues related to `faststream.confluent` module label Sep 28, 2026

@IvanKirpichnikov IvanKirpichnikov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi. Sorry it took so long.

The idea of using to_async in __post_init__ didn’t really work for me. It ended up feeling a bit cumbersome. Let’s go back to your approach.

Second, why are you wrapping it in _build_fastdepends_model? Let’s do it in __init__ instead. In theory, nothing should break.

Third, the tests.

Let’s write e2e tests. The current tests are fragile because you monkeypatch a lot of things and call private methods.

I think it would be better to write e2e tests like this:

async def test_subscriber_exception_handler_true_suppresses_error(
    self,
    queue: str,
    event: Event,
    mock: MagicMock,
) -> None:
    error = RuntimeError()

    async def exception_handler(exc: BaseException) -> bool:
        mock(exc)
        return True

    broker = self.get_broker()

    args, kwargs = self.get_subscriber_params(queue, exception_handler=exception_handler)

    @broker.subscriber(*args, **kwargs)
    async def handler(msg: Any) -> NoReturn:
        event.set()
        raise error

    async with self.patch_broker(broker) as br:
        await asyncio.wait(
            (
                asyncio.create_task(br.publish(queue, None)),
                asyncio.create_task(event.wait()),
            ),
            timeout=self.timeout,
        )

    mock.assert_called_one_with(error)

@IvanKirpichnikov IvanKirpichnikov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We also need to add another global exception handler at the FastStream level, which will also be taken into account when handling errors, as the very last one. Tests will need to be added for it.

Comment thread faststream/_internal/configs/broker.py Outdated
Comment thread faststream/_internal/broker/broker.py Outdated
Comment thread faststream/_internal/configs/endpoint.py Outdated
Comment thread faststream/_internal/endpoint/subscriber/usecase.py Outdated
Comment thread faststream/kafka/broker/broker.py Outdated
Comment thread tests/brokers/base/exception_handlers.py Outdated
Comment thread tests/brokers/base/exception_handlers.py
Comment thread tests/brokers/kafka/test_exception_handlers.py
Comment thread tests/brokers/base/exception_handlers.py

@IvanKirpichnikov IvanKirpichnikov left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And add docs

Comment thread faststream/app.py Outdated
Comment thread tests/brokers/base/exception_handlers.py
Comment thread faststream/_internal/endpoint/subscriber/usecase.py Outdated
Comment thread faststream/_internal/endpoint/subscriber/usecase.py Outdated
Comment thread faststream/_internal/endpoint/subscriber/usecase.py Outdated
Comment thread faststream/kafka/subscriber/factory.py Outdated
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Oct 13, 2026
exc: BaseException | None,
_exc_tb: TracebackType | None,
) -> bool:
if not isinstance(exc, Exception) or isinstance(exc, (StopConsume, SystemExit)):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you tell me why this particular condition is in place?

self._outer_config.broker_exception_handler,
self._app_exception_handler,
):
if handler is not None and await handler(exc, context__=context):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

may remove inject context__

# reserve place for context scope under the middlewares __aexit__
# because middlewares should be exited before context scope release
message_scope = stack.enter_context(ExitStack())
stack.push_async_exit(self._handle_exception)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This won’t work, will it?

call("app", error),
]

@pytest.mark.parametrize("handled_by", ("subscriber", "broker"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should split this test into two, because it’s hard to read the test with such parametrization.

mock.assert_called_once_with("hello")
assert exc_info.value is error

@pytest.mark.parametrize("handler_level", ("subscriber", "broker"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should split this test into two, because it’s hard to read the test with such parametrization.

@IvanKirpichnikov

Copy link
Copy Markdown
Collaborator

and pull main

DMINQ added 3 commits October 24, 2026 18:12
# Conflicts:
#	faststream/_internal/configs/broker.py
…-handlers

# Conflicts:
#	faststream/_internal/endpoint/subscriber/usecase.py

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AioKafka Issues related to `faststream.kafka` module Confluent Issues related to `faststream.confluent` module documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants