Skip to content

fix: give error handlers an open container so @inject works in them - #62

Merged
lesnik512 merged 1 commit into
mainfrom
fix/inject-in-error-handlers
Oct 17, 2026
Merged

lesnik512 merged 1 commit into
mainfrom
fix/inject-in-error-handlers

Conversation

@lesnik512

Copy link
Copy Markdown
Member

The DI middleware is an outer middleware on dispatcher.update. aiogram's own ErrorsMiddleware is registered there first, so it wraps ours. When a handler raises, our middleware closes the update's child container. ErrorsMiddleware then calls the error handlers with the same data dict, which still holds the closed child. An @inject error handler that resolves a REQUEST-scoped dependency raised ContainerClosedError, and that error replaced the handler's original exception. auto_inject=True wraps error handlers too, so it had the same problem.

The same middleware instance is now also an outer middleware on dispatcher.errors. For an ErrorEvent it binds the failing Update and that update's event, so an error handler gets an open child of its own. Error handling also counts as in flight, so the shutdown wait covers it.

The error handler gets a second child, not the failing update's. Its REQUEST-scoped instances are fresh, and the first child's finalizers have already run by then. Sharing the first child would mean inserting our middleware ahead of ErrorsMiddleware, and aiogram's MiddlewareManager has no public insert. Its list is private.

The new test raises in a message handler and resolves a REQUEST dependency plus the event type in an @inject error handler. On main it fails with ContainerClosedError. All 53 tests pass with 100% coverage. CONTEXT.md now describes the second child.

@lesnik512
lesnik512 merged commit cb8af6e into main Oct 17, 2026
12 checks passed
@lesnik512
lesnik512 deleted the fix/inject-in-error-handlers branch October 17, 2026 19:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant