Skip to content

fix(flask): handle missing segment gracefully in after_request - #492

Open
reginaldalfret wants to merge 1 commit into
aws:masterfrom
reginaldalfret:fix-405-flask-after-request-missing-segment
Open

reginaldalfret wants to merge 1 commit into
aws:masterfrom
reginaldalfret:fix-405-flask-after-request-missing-segment

Conversation

@reginaldalfret

Copy link
Copy Markdown

Description

When Flask executes before_request functions, if an earlier extension raises an exception or returns a response early, subsequent before_request callbacks (including X-Ray's) are skipped, while after_request callbacks are still executed.

In XRayMiddleware._after_request, segment.put_http_meta(...) previously assumed that current_segment() or current_subsegment() is always present, raising AttributeError: 'NoneType' object has no attribute 'put_http_meta' when no segment is open.

This PR adds a try...except... if not segment: return response check in _after_request, matching the existing guard pattern in _teardown_request, so un-traced or early-terminated responses are safely returned without crashing.

Testing

  • Added regression test test_missing_segment_in_after_request in tests/ext/flask/test_flask.py confirming early before_request responses are handled without error.
  • Verified all 12 flask extension tests pass.
  • Verified core recorder/patcher test suite passes (48 tests passed).

Fixes #405

When an earlier Flask before_request extension short-circuits or raises, X-Ray before_request might not create a segment. Guard _after_request to return the response gracefully when no segment is open, matching the pattern in _teardown_request.

Fixes aws#405
@reginaldalfret
reginaldalfret requested a review from a team as a code owner September 25, 2026 05:01
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.

Flask middleware errors when an earlier Flask extension throws an exception in a before_request method

1 participant