Skip to content

fix: avoid JSON::ParserError for all server errors #582

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

Merged
merged 2 commits into from
Apr 21, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/twilio-ruby/http/http_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ def _request(request)
@last_response = nil

response = send(request)
if response.status == 504
object = { message: 'Request timeout', code: 504 }.to_json
if (500..599).include?(response.status)
object = { message: "Server error (#{response.status})", code: response.status }.to_json
elsif response.body && !response.body.empty?
object = response.body
elsif response.status == 400
Expand Down
15 changes: 8 additions & 7 deletions spec/http/http_client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -143,19 +143,20 @@
expect(@client.last_response).to be_nil
end

context 'when the response returns a timeout' do
context 'when there is a server error' do
let(:faraday_connection) { Faraday::Connection.new }
let(:twilio_response) { @client.request('host', 'port', 'GET', 'url') }

before do
faraday_connection = Faraday::Connection.new

allow(Faraday).to receive(:new).and_return(faraday_connection)
allow(faraday_connection).to receive(:send).and_return(double('response', status: 504, body: { message: 'any message' }, headers: {}))
end

it 'adds a Request timeout message to the response and avoids non-JSON response to raise Json::ParserError' do
expect(twilio_response.body).to eq({ 'message' => 'Request timeout', 'code' => 504 })
expect(twilio_response.status_code).to eq 504
(500..599).each do |status_code|
it 'generates a JSON-parseable body' do
allow(faraday_connection).to receive(:send).and_return(double('response', status: status_code, body: { message: 'any message' }, headers: {}))
expect(twilio_response.body).to eq({ 'message' => "Server error (#{status_code})", 'code' => status_code })
expect(twilio_response.status_code).to eq status_code
end
end
end
end