diff --git a/lib/typesense/api_call.rb b/lib/typesense/api_call.rb index 408409b..e7720da 100644 --- a/lib/typesense/api_call.rb +++ b/lib/typesense/api_call.rb @@ -98,11 +98,7 @@ def perform_request(method, endpoint, query_parameters: nil, body_parameters: ni @logger.debug "Request #{method}:#{uri_for(endpoint, node)} to Node #{node[:index]} was successfully made (at the network layer). response.status was #{response.status}." - parsed_response = if response.headers && (response.headers['content-type'] || '').include?('application/json') - JSON.parse(response.body) - else - response.body - end + parsed_response = parse_response_body(response) # If response is 2xx return the object, else raise the response as an exception return parsed_response if response.status.between?(200, 299) @@ -133,6 +129,18 @@ def perform_request(method, endpoint, query_parameters: nil, body_parameters: ni private + # An error response with an unparseable JSON body returns nil, so that the status + # still decides which exception is raised and whether the request is retried. + def parse_response_body(response) + return response.body unless response.headers && (response.headers['content-type'] || '').include?('application/json') + + JSON.parse(response.body) + rescue JSON::ParserError + raise if response.status.between?(200, 299) + + nil + end + # Faraday 2.9.2 and later only treat a request URL as absolute when it starts # with a lower-case "http://" or "https://". def uri_for(endpoint, node) diff --git a/spec/typesense/api_call_spec.rb b/spec/typesense/api_call_spec.rb index b7f311d..c5fd2d6 100644 --- a/spec/typesense/api_call_spec.rb +++ b/spec/typesense/api_call_spec.rb @@ -244,6 +244,36 @@ end end + describe 'unparseable JSON bodies' do + def stub_node(index, status:, body:) + stub_request(:get, api_call.send(:uri_for, '/', typesense.configuration.nodes[index])) + .to_return(status: status, body: body, headers: { 'Content-Type' => 'application/json' }) + end + + it 'retries the next node when a server error has an empty body' do + node_0_stub = stub_node(0, status: 503, body: '') + node_1_stub = stub_node(1, status: 200, body: JSON.dump('hits' => [])) + + expect(api_call.get('/')).to eq('hits' => []) + expect(node_0_stub).to have_been_requested.once + expect(node_1_stub).to have_been_requested.once + end + + it 'raises the error class for the status when the error body is not valid JSON' do + stub_node(0, status: 404, body: 'Not Found') + + expect { api_call.get('/') }.to raise_error(Typesense::Error::ObjectNotFound, 'Error') do |error| + expect(error.data[:response].body).to eq('Not Found') + end + end + + it 'still raises a parser error for a successful response' do + stub_node(0, status: 200, body: '{') + + expect { api_call.get('/') }.to raise_error(JSON::ParserError) + end + end + describe '#post' do it_behaves_like 'General error handling', :post it_behaves_like 'Node selection', :post