diff --git a/sentry_sdk/integrations/stdlib.py b/sentry_sdk/integrations/stdlib.py index 287c8cb272..d388c5bca6 100644 --- a/sentry_sdk/integrations/stdlib.py +++ b/sentry_sdk/integrations/stdlib.py @@ -127,11 +127,13 @@ def getresponse(self, *args, **kwargs): if span is None: return real_getresponse(self, *args, **kwargs) - rv = real_getresponse(self, *args, **kwargs) + try: + rv = real_getresponse(self, *args, **kwargs) - span.set_http_status(int(rv.status)) - span.set_data("reason", rv.reason) - span.finish() + span.set_http_status(int(rv.status)) + span.set_data("reason", rv.reason) + finally: + span.finish() return rv diff --git a/tests/integrations/stdlib/test_httplib.py b/tests/integrations/stdlib/test_httplib.py index c327331608..200b282f53 100644 --- a/tests/integrations/stdlib/test_httplib.py +++ b/tests/integrations/stdlib/test_httplib.py @@ -1,5 +1,6 @@ import random from http.client import HTTPConnection, HTTPSConnection +from socket import SocketIO from urllib.request import urlopen from unittest import mock @@ -342,3 +343,35 @@ def test_span_origin(sentry_init, capture_events): assert event["spans"][0]["op"] == "http.client" assert event["spans"][0]["origin"] == "auto.http.stdlib.httplib" + + +def test_http_timeout(monkeypatch, sentry_init, capture_envelopes): + mock_readinto = mock.Mock(side_effect=TimeoutError) + monkeypatch.setattr(SocketIO, "readinto", mock_readinto) + + sentry_init(traces_sample_rate=1.0) + + envelopes = capture_envelopes() + + with start_transaction(op="op", name="name"): + try: + conn = HTTPSConnection("www.squirrelchasers.com") + conn.request("GET", "/top-chasers") + conn.getresponse() + except Exception: + pass + + items = [ + item + for envelope in envelopes + for item in envelope.items + if item.type == "transaction" + ] + assert len(items) == 1 + + transaction = items[0].payload.json + assert len(transaction["spans"]) == 1 + + span = transaction["spans"][0] + assert span["op"] == "http.client" + assert span["description"] == "GET https://www.squirrelchasers.com/top-chasers"