Skip to content

Commit

Permalink
tracing: fix http client synchronous errors causing spans to not fini…
Browse files Browse the repository at this point in the history
…sh (#5294)

* ensure client http request span closes if request completely fails
  • Loading branch information
wconti27 authored Feb 19, 2025
1 parent 00043df commit 18e840f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
5 changes: 5 additions & 0 deletions packages/datadog-instrumentations/src/http/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ function patch (http, methodName) {
} catch (e) {
ctx.error = e
errorChannel.publish(ctx)
// if the initial request failed, ctx.req will be unset, we must close the span here
// fix for: https://github.com/DataDog/dd-trace-js/issues/5016
if (!ctx.req) {
finish()
}
throw e
} finally {
endChannel.publish(ctx)
Expand Down
4 changes: 3 additions & 1 deletion packages/datadog-plugin-http/src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ class HttpClientPlugin extends ClientPlugin {
addResponseHeaders(res, span, this.config)
}

addRequestHeaders(req, span, this.config)
if (req) {
addRequestHeaders(req, span, this.config)
}

this.config.hooks.request(span, req, res)

Expand Down
18 changes: 18 additions & 0 deletions packages/datadog-plugin-http/test/client.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,24 @@ describe('Plugin', () => {
})
})
}

it('should record unfinished http requests as error spans', done => {
agent
.use(traces => {
expect(traces[0][0]).to.have.property('error', 1)
expect(traces[0][0].meta).to.not.have.property('http.status_code')
})
.then(done)
.catch(done)

try {
http.request('http://httpbin.org/get', { headers: { BadHeader: 'a\nb' } }, res => {
res.on('data', () => { })
})
} catch {
// expected to throw error
}
})
})

describe('with late plugin initialization and an external subscriber', () => {
Expand Down

0 comments on commit 18e840f

Please sign in to comment.