Skip to content

Commit

Permalink
Merge pull request #1 from rootstrap/include_request_info_in_raise_er…
Browse files Browse the repository at this point in the history
…ror_middleware

Include request info in exceptions raised by RaiseError Middleware
  • Loading branch information
SandroDamilano committed Sep 16, 2020
2 parents 9af091f + 0dc35cf commit 4ad788d
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
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

0 comments on commit 4ad788d

Please sign in to comment.