diff --git a/lib/mollie/client.rb b/lib/mollie/client.rb index 63d1686..068c243 100644 --- a/lib/mollie/client.rb +++ b/lib/mollie/client.rb @@ -133,7 +133,7 @@ def perform_http_call(http_method, api_method, id = nil, http_body = {}, query = exception = ResourceNotFoundError.new(json, response) raise exception else - json = JSON.parse(response.body) + json = parse_body(response) exception = Mollie::RequestError.new(json, response) raise exception end @@ -162,5 +162,15 @@ def build_nested_query(value, prefix = nil) def escape(s) URI.encode_www_form_component(s) end + + def parse_body(response) + JSON.parse(response.body) + rescue JSON::ParserError => e + { + "status" => response.code.to_i, + "title" => response.message, + "detail" => "Unable to parse JSON: #{e.message}" + } + end end end diff --git a/test/mollie/client_test.rb b/test/mollie/client_test.rb index afe8894..641385e 100644 --- a/test/mollie/client_test.rb +++ b/test/mollie/client_test.rb @@ -177,5 +177,18 @@ def test_404_response assert_equal(json['field'], e.field) assert_equal(json['_links'], e.links) end + + def test_invalid_response + stub_request(:post, 'https://api.mollie.com/v2/my-method') + .to_return(status: [500, "Internal server error"], body: "

Internal server error

", headers: {}) + + e = assert_raise Mollie::RequestError do + client.perform_http_call('POST', 'my-method', nil, {}) + end + + assert_equal(500, e.status) + assert_equal('Internal server error', e.title) + assert_match(/Unable to parse JSON:.*/, e.detail) + end end end