Skip to content

Commit cd0fed7

Browse files
armisaelcarolabadeersrprash
authored
Fix UnboundLocalError when aiohttp server raises a CancelledError (#356)
Co-authored-by: Carol Abadeer <[email protected]> Co-authored-by: Prashant Srivastava <[email protected]>
1 parent 699ed0c commit cd0fed7

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

Diff for: aws_xray_sdk/ext/aiohttp/middleware.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ async def middleware(request, handler):
6767
# Non 2XX responses are raised as HTTPExceptions
6868
response = exc
6969
six.raise_from(exc, exc)
70-
except Exception as exc:
70+
except BaseException as exc:
7171
# Store exception information including the stacktrace to the segment
7272
response = None
7373
segment.put_http_meta(http.STATUS, 500)

Diff for: tests/ext/aiohttp/test_middleware.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,10 @@ async def handle_unauthorized(self, request: web.Request) -> web.Response:
7575

7676
async def handle_exception(self, request: web.Request) -> web.Response:
7777
"""
78-
Handle /exception which raises a KeyError
78+
Handle /exception which raises a CancelledError; this is important, as starting from python 3.8 CancelledError
79+
extends BaseException instead of Exception
7980
"""
80-
return {}['key']
81+
raise asyncio.CancelledError()
8182

8283
async def handle_delay(self, request: web.Request) -> web.Response:
8384
"""
@@ -213,8 +214,8 @@ async def test_exception(test_client, loop, recorder):
213214
"""
214215
client = await test_client(ServerTest.app(loop=loop))
215216

216-
resp = await client.get('/exception')
217-
await resp.text() # Need this to trigger Exception
217+
with pytest.raises(Exception):
218+
await client.get('/exception')
218219

219220
segment = recorder.emitter.pop()
220221
assert not segment.in_progress
@@ -227,7 +228,7 @@ async def test_exception(test_client, loop, recorder):
227228
assert request['url'] == 'http://127.0.0.1:{port}/exception'.format(port=client.port)
228229
assert request['client_ip'] == '127.0.0.1'
229230
assert response['status'] == 500
230-
assert exception.type == 'KeyError'
231+
assert exception.type == 'CancelledError'
231232

232233

233234
async def test_unhauthorized(test_client, loop, recorder):

0 commit comments

Comments
 (0)