Skip to content

Commit

Permalink
Improve request info in exceptions raised by RaiseError Middleware (l…
Browse files Browse the repository at this point in the history
  • Loading branch information
willianzocolau authored and jrochkind committed Dec 20, 2021
1 parent c2ed23d commit 7d15a00
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions lib/faraday/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def response_body
# :body - Optional string HTTP response body.
# :request - Hash
# :method - Symbol with the request HTTP method.
# :url - URI object with the url requested.
# :url_path - String with the url path requested.
# :params - String key/value hash of query params
# present in the request.
Expand Down
8 changes: 7 additions & 1 deletion lib/faraday/response/raise_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,19 @@ def response_values(env)
body: env.body,
request: {
method: env.method,
url: env.url,
url_path: env.url.path,
params: env.params,
params: query_params(env),
headers: env.request_headers,
body: env.request_body
}
}
end

def query_params(env)
env.request.params_encoder ||= Faraday::Utils.default_params_encoder
env.params_encoder.decode(env.url.query)
end
end
end
end
Expand Down
11 changes: 7 additions & 4 deletions spec/faraday/response/raise_error_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -139,27 +139,30 @@
Faraday.new do |b|
b.response :raise_error
b.adapter :test do |stub|
stub.post('request?full=true', request_body, request_headers) do
stub.post(url, request_body, request_headers) do
[400, { 'X-Reason' => 'because' }, 'keep looking']
end
end
end
end
let(:request_body) { JSON.generate({ 'item' => 'sth' }) }
let(:request_headers) { { 'Authorization' => 'Basic 123' } }
let(:url_path) { 'request' }
let(:query_params) { 'full=true' }
let(:url) { "#{url_path}?#{query_params}" }

subject(:perform_request) do
conn.post 'request' do |req|
conn.post url do |req|
req.headers['Authorization'] = 'Basic 123'
req.params[:full] = true
req.body = request_body
end
end

it 'returns the request info in the exception' do
expect { perform_request }.to raise_error(Faraday::BadRequestError) do |ex|
expect(ex.response[:request][:method]).to eq(:post)
expect(ex.response[:request][:url_path]).to eq('/request')
expect(ex.response[:request][:url]).to eq(URI("http:/#{url}"))
expect(ex.response[:request][:url_path]).to eq("/#{url_path}")
expect(ex.response[:request][:params]).to eq({ 'full' => 'true' })
expect(ex.response[:request][:headers]).to match(a_hash_including(request_headers))
expect(ex.response[:request][:body]).to eq(request_body)
Expand Down

0 comments on commit 7d15a00

Please sign in to comment.