Skip to content
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

Catch invalid JSON response and raise Mollie::RequestError #181

Closed
wants to merge 2 commits into from
Closed
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
12 changes: 11 additions & 1 deletion lib/mollie/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
13 changes: 13 additions & 0 deletions test/mollie/client_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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: "<h1>Internal server error</h1>", 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
Loading