@@ -706,13 +706,16 @@ def __call__(
706706 self ._sem_conv_opt_in_mode ,
707707 )
708708 iterable = self .wsgi (environ , start_response )
709- return _iterate_and_close_with_span (iterable , span , token )
709+ return _end_span_after_iterating (iterable , span , token )
710710 except Exception as ex :
711711 if _report_new (self ._sem_conv_opt_in_mode ):
712712 req_attrs [ERROR_TYPE ] = type (ex ).__qualname__
713713 if span .is_recording ():
714714 span .set_attribute (ERROR_TYPE , type (ex ).__qualname__ )
715715 span .set_status (Status (StatusCode .ERROR , str (ex )))
716+ span .end ()
717+ if token is not None :
718+ context .detach (token )
716719 raise
717720 finally :
718721 duration_s = default_timer () - start
@@ -736,16 +739,13 @@ def __call__(
736739 context = active_metric_ctx ,
737740 )
738741 self .active_requests_counter .add (- 1 , active_requests_count_attrs )
739- span .end ()
740- if token is not None :
741- context .detach (token )
742742
743743
744744# Put this in a subfunction to not delay the call to the wrapped
745745# WSGI application (instrumentation should change the application
746746# behavior as little as possible).
747- def _iterate_and_close_with_span (
748- iterable : Iterable [T ], span : trace .Span
747+ def _end_span_after_iterating (
748+ iterable : Iterable [T ], span : trace .Span , token : object
749749) -> Iterable [T ]:
750750 try :
751751 with trace .use_span (span ):
@@ -754,6 +754,9 @@ def _iterate_and_close_with_span(
754754 close = getattr (iterable , "close" , None )
755755 if close :
756756 close ()
757+ span .end ()
758+ if token is not None :
759+ context .detach (token )
757760
758761
759762# TODO: inherit from opentelemetry.instrumentation.propagators.Setter
0 commit comments