fix(fastapi): add recursion guard to prevent infinite exception capture#5735
fix(fastapi): add recursion guard to prevent infinite exception capture#5735Aliipou wants to merge 1 commit intogetsentry:masterfrom
Conversation
…re loop Adds a ContextVar-based recursion guard (_sentry_exception_handling) to the Starlette/FastAPI integration's _capture_exception function so that exceptions raised inside Sentry's own patched exception handler do not re-trigger capture_exception, preventing an infinite recursive loop (issue getsentry#5025). Also adds a regression test in tests/integrations/fastapi/test_fastapi.py that verifies the guard works when a FastAPI exception handler raises a secondary exception. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Semver Impact of This PR🟢 Patch (bug fixes) 📋 Changelog PreviewThis is how your changes will appear in the changelog. New Features ✨
Bug Fixes 🐛Anthropic
Other
Documentation 📚
Internal Changes 🔧
Other
🤖 This preview updates automatically when you update the PR. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
| assert len(captured_exceptions) <= 5, ( | ||
| "Too many exception events captured — possible recursion: %d events" | ||
| % len(captured_exceptions) | ||
| ) |
There was a problem hiding this comment.
Test never exercises the recursion guard code path
Medium Severity
The test claims to verify the ContextVar recursion guard, but the guard is never activated during the test. The _capture_exception function (where the guard lives) is only called when is_http_server_error is True, which requires the exception to have a status_code attribute. The test's PrimaryError has no status_code, so _capture_exception is never called, the guard is never set, and the test passes with or without the guard. If someone later removes the guard, this test would still pass, leaving the fix effectively untested.


Fixes #5025
Adds a
ContextVar-based recursion guard to the FastAPI/Starlette integration so that exceptions raised inside Sentry's own exception handler do not re-trigger capture, preventing an infinite recursive loop.Adds a test case that verifies the guard works when a FastAPI exception handler raises a secondary exception.