Skip to content

Commit

Permalink
feat: Propagate response attributes on Faraday::Error
Browse files Browse the repository at this point in the history
The current `Faraday` middleware won't report `http.status_code` in
cases where an error is raised via another middleware (such as
`:raise_error` or `:json`).

This adds a special case for subclasses of `Faraday::Error` which have
response information available, so that `http.status_code` the span
status are still added to the span.
  • Loading branch information
CGA1123 committed Mar 22, 2024
1 parent 9d1b947 commit d82fc15
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ def call(env)
) do |span|
OpenTelemetry.propagation.inject(env.request_headers)

app.call(env).on_complete { |resp| trace_response(span, resp) }
app.call(env).on_complete { |resp| trace_response(span, resp.status) }
rescue ::Faraday::Error => e
trace_response(span, e.response[:status]) if e.response

raise
end
end

Expand All @@ -62,9 +66,9 @@ def tracer
Faraday::Instrumentation.instance.tracer
end

def trace_response(span, response)
span.set_attribute('http.status_code', response.status)
span.status = OpenTelemetry::Trace::Status.error unless (100..399).cover?(response.status.to_i)
def trace_response(span, status)
span.set_attribute('http.status_code', status)
span.status = OpenTelemetry::Trace::Status.error unless (100..399).cover?(status.to_i)
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,5 +178,25 @@
)
end
end

describe 'when faraday raises an error' do
let(:client) do
Faraday.new do |builder|
builder.response :raise_error
builder.adapter(:test) do |stub|
stub.get('/not_found') { |_| [404, {}, 'NOT FOUND'] }
end
end
end

it 'adds response attributes' do
assert_raises Faraday::Error do
client.get('/not_found')
end

_(span.attributes['http.status_code']).must_equal 404
_(span.status.code).must_equal OpenTelemetry::Trace::Status::ERROR
end
end
end
end

0 comments on commit d82fc15

Please sign in to comment.