Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include request info in exceptions raised by RaiseError Middleware #1181

Merged
merged 2 commits into from Sep 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/faraday/error.rb
Expand Up @@ -38,6 +38,14 @@ def inspect
# :headers - String key/value hash of HTTP response header
# values.
# :body - Optional string HTTP response body.
# :request - Hash
# :method - Symbol with the request HTTP method.
# :url_path - String with the url path requested.
# :params - String key/value hash of query params
# present in the request.
# :headers - String key/value hash of HTTP request
# header values.
# :body - String HTTP request body.
#
# If a subclass has to call this, then it should pass a string message
# to `super`. See NilStatusError.
Expand Down
13 changes: 12 additions & 1 deletion lib/faraday/response/raise_error.rb
Expand Up @@ -38,7 +38,18 @@ def on_complete(env)
end

def response_values(env)
{ status: env.status, headers: env.response_headers, body: env.body }
{
status: env.status,
headers: env.response_headers,
body: env.body,
request: {
method: env.method,
url_path: env.url.path,
params: env.params,
headers: env.request_headers,
body: env.request_body
}
}
end
end
end
Expand Down
33 changes: 33 additions & 0 deletions spec/faraday/response/raise_error_spec.rb
Expand Up @@ -103,4 +103,37 @@
expect(ex.response[:status]).to eq(500)
end
end

describe 'request info' do
let(:conn) do
Faraday.new do |b|
b.response :raise_error
b.adapter :test do |stub|
stub.post('request?full=true', 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' } }

subject(:perform_request) do
conn.post 'request' 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][: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)
end
end
end
end