From 3ee9e8fcc479e69b36262ab8e0ddbf670644025c Mon Sep 17 00:00:00 2001 From: Maychell Date: Mon, 26 Apr 2021 19:53:05 -0300 Subject: [PATCH] fix: JSON parser error on timeout response (#554) --- lib/twilio-ruby/http/http_client.rb | 4 +++- spec/http/http_client_spec.rb | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/twilio-ruby/http/http_client.rb b/lib/twilio-ruby/http/http_client.rb index 5333b142f..f17f8b2da 100644 --- a/lib/twilio-ruby/http/http_client.rb +++ b/lib/twilio-ruby/http/http_client.rb @@ -34,7 +34,9 @@ def _request(request) @last_response = nil response = send(request) - if response.body && !response.body.empty? + if response.status == 504 + object = { message: 'Request timeout', code: 504 }.to_json + elsif response.body && !response.body.empty? object = response.body elsif response.status == 400 object = { message: 'Bad request', code: 400 }.to_json diff --git a/spec/http/http_client_spec.rb b/spec/http/http_client_spec.rb index 1d1aa8dc1..de4927ee2 100644 --- a/spec/http/http_client_spec.rb +++ b/spec/http/http_client_spec.rb @@ -119,4 +119,20 @@ expect { @client.request('host', 'port', 'GET', 'url', nil, nil, {}, ['a', 'b']) }.to raise_exception(Twilio::REST::TwilioError) expect(@client.last_response).to be_nil end + + context 'when the response returns a timeout' do + 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 + end + end end