@@ -11,7 +11,7 @@ import {
1111 SEMATTRS_NET_HOST_PORT ,
1212 SEMATTRS_NET_PEER_IP ,
1313} from '@opentelemetry/semantic-conventions' ;
14- import type { AggregationCounts , Client , Scope , SpanAttributes } from '@sentry/core' ;
14+ import type { AggregationCounts , Client , Scope , SpanAttributes , SpanStatus } from '@sentry/core' ;
1515import {
1616 debug ,
1717 generateSpanId ,
@@ -251,31 +251,33 @@ export function instrumentServer(
251251
252252 // After 'error', no further events other than 'close' should be emitted.
253253 let isEnded = false ;
254- response . on ( 'close' , ( ) => {
254+ function endSpan ( status : SpanStatus ) : void {
255255 if ( isEnded ) {
256256 return ;
257257 }
258258
259259 isEnded = true ;
260- const newAttributes = getIncomingRequestAttributesOnResponse ( request , response ) ;
261- span . setAttributes ( newAttributes ) ;
262- span . setStatus ( getSpanStatusFromHttpCode ( response . statusCode ) ) ;
263260
264- span . end ( ) ;
265- } ) ;
266- response . on ( errorMonitor , ( ) => {
267- if ( isEnded ) {
268- return ;
269- }
270-
271- isEnded = true ;
272261 const newAttributes = getIncomingRequestAttributesOnResponse ( request , response ) ;
273262 span . setAttributes ( newAttributes ) ;
263+ span . setStatus ( status ) ;
264+ span . end ( ) ;
274265
275- const status = getSpanStatusFromHttpCode ( response . statusCode ) ;
266+ // Update the transaction name if the route has changed
267+ if ( newAttributes [ 'http.route' ] ) {
268+ getIsolationScope ( ) . setTransactionName (
269+ `${ request . method ?. toUpperCase ( ) || 'GET' } ${ newAttributes [ 'http.route' ] } ` ,
270+ ) ;
271+ }
272+ }
276273
277- span . setStatus ( status . code === SPAN_STATUS_ERROR ? status : { code : SPAN_STATUS_ERROR } ) ;
278- span . end ( ) ;
274+ response . on ( 'close' , ( ) => {
275+ endSpan ( getSpanStatusFromHttpCode ( response . statusCode ) ) ;
276+ } ) ;
277+ response . on ( errorMonitor , ( ) => {
278+ const httpStatus = getSpanStatusFromHttpCode ( response . statusCode ) ;
279+ // Ensure we def. have an error status here
280+ endSpan ( httpStatus . code === SPAN_STATUS_ERROR ? httpStatus : { code : SPAN_STATUS_ERROR } ) ;
279281 } ) ;
280282
281283 return target . apply ( thisArg , args ) ;
@@ -544,7 +546,8 @@ function getIncomingRequestAttributesOnResponse(request: IncomingMessage, respon
544546 newAttributes [ 'http.status_text' ] = ( statusMessage || '' ) . toUpperCase ( ) ;
545547
546548 if ( rpcMetadata ?. type === RPCType . HTTP && rpcMetadata . route !== undefined ) {
547- newAttributes [ ATTR_HTTP_ROUTE ] = rpcMetadata . route ;
549+ const routeName = rpcMetadata . route ;
550+ newAttributes [ ATTR_HTTP_ROUTE ] = routeName ;
548551 }
549552
550553 return newAttributes ;
0 commit comments