Skip to content

Commit c7c365a

Browse files
authored
feat(tracing): Track span status for fetch requests (#2835)
1 parent b13b2e5 commit c7c365a

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

packages/tracing/src/browser/request.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ export interface FetchData {
4848
// span_id
4949
__span?: string;
5050
};
51+
response?: Response;
5152
startTimestamp: number;
5253
endTimestamp?: number;
5354
}
@@ -137,6 +138,10 @@ export function _fetchCallback(
137138
if (handlerData.endTimestamp && handlerData.fetchData.__span) {
138139
const span = spans[handlerData.fetchData.__span];
139140
if (span) {
141+
const response = handlerData.response;
142+
if (response) {
143+
span.setHttpStatus(response.status);
144+
}
140145
span.finish();
141146

142147
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { BrowserClient } from '@sentry/browser';
22
import { Hub, makeMain } from '@sentry/hub';
33

4-
import { Span, Transaction } from '../../src';
4+
import { Span, SpanStatus, Transaction } from '../../src';
55
import { _fetchCallback, FetchData, registerRequestInstrumentation } from '../../src/browser/request';
66
import { addExtensionMethods } from '../../src/hubextensions';
77

@@ -157,4 +157,33 @@ describe('_fetchCallback()', () => {
157157
fail('Transaction does not have span recorder');
158158
}
159159
});
160+
161+
it('sets response status on finish', () => {
162+
const shouldCreateSpan = (_: string): boolean => true;
163+
const data: FetchData = {
164+
args: ['/users'],
165+
fetchData: {
166+
method: 'GET',
167+
url: '/users',
168+
},
169+
startTimestamp: 1595509730275,
170+
};
171+
const spans: Record<string, Span> = {};
172+
173+
// Start fetch request
174+
_fetchCallback(data, shouldCreateSpan, spans);
175+
176+
const newData = {
177+
...data,
178+
endTimestamp: data.startTimestamp + 12343234,
179+
response: { status: 404 } as Response,
180+
};
181+
// End fetch request
182+
_fetchCallback(newData, shouldCreateSpan, spans);
183+
if (transaction.spanRecorder) {
184+
expect(transaction.spanRecorder.spans[1].status).toBe(SpanStatus.fromHttpCode(404));
185+
} else {
186+
fail('Transaction does not have span recorder');
187+
}
188+
});
160189
});

0 commit comments

Comments
 (0)