Skip to content

Commit e0137ef

Browse files
committed
fix(tracing): ignore the xhr response if its request is not being tracked
1 parent eaf2e81 commit e0137ef

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

packages/tracing/src/browser/request.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,9 @@ export function xhrCallback(
216216
const xhr = handlerData.xhr.__sentry_xhr__;
217217

218218
// check first if the request has finished and is tracked by an existing span which should now end
219-
if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) {
219+
if (handlerData.endTimestamp) {
220+
if (!handlerData.xhr.__sentry_xhr_span_id__) return;
221+
220222
const span = spans[handlerData.xhr.__sentry_xhr_span_id__];
221223
if (span) {
222224
span.setHttpStatus(xhr.status_code);

packages/tracing/test/browser/request.test.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,12 @@ describe('callbacks', () => {
4848
let transaction: Transaction;
4949
const alwaysCreateSpan = () => true;
5050
const neverCreateSpan = () => false;
51+
const startTimestamp = 1356996072000;
52+
const endTimestamp = 1356996072000;
5153
const fetchHandlerData: FetchData = {
5254
args: ['http://dogs.are.great/', {}],
5355
fetchData: { url: 'http://dogs.are.great/', method: 'GET' },
54-
startTimestamp: 1356996072000,
56+
startTimestamp,
5557
};
5658
const xhrHandlerData: XHRData = {
5759
xhr: {
@@ -66,9 +68,8 @@ describe('callbacks', () => {
6668
// setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
6769
setRequestHeader,
6870
},
69-
startTimestamp: 1353501072000,
71+
startTimestamp,
7072
};
71-
const endTimestamp = 1356996072000;
7273

7374
beforeAll(() => {
7475
hub = new Hub(new BrowserClient({ tracesSampleRate: 1 }));
@@ -263,5 +264,26 @@ describe('callbacks', () => {
263264

264265
expect(newSpan!.status).toBe(spanStatusfromHttpCode(404));
265266
});
267+
268+
it('ignores response with no associated span', () => {
269+
// the request might be missed somehow. E.g. if it was sent before tracing gets enabled.
270+
271+
const postRequestXHRHandlerData = {
272+
...{
273+
xhr: {
274+
__sentry_xhr__: xhrHandlerData.xhr.__sentry_xhr__,
275+
},
276+
},
277+
startTimestamp,
278+
endTimestamp,
279+
};
280+
281+
// in that case, the response coming back will be ignored
282+
xhrCallback(postRequestXHRHandlerData, alwaysCreateSpan, {});
283+
284+
const newSpan = transaction.spanRecorder?.spans[1];
285+
286+
expect(newSpan).toBeUndefined();
287+
});
266288
});
267289
});

0 commit comments

Comments
 (0)