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

Handle JSON::ParserError when http response is HTML and raise ShopifyAPI::Errors::HttpResponseError #1113

Merged
merged 7 commits into from
Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Note: For changes to the API, see https://shopify.dev/changelog?filter=api

## Unreleased

- [#1113](https://github.com/Shopify/shopify-api-ruby/pull/1113) Handle JSON::ParserError when http response is HTML and raise ShopifyAPI::Errors::HttpResponseError
- [#1098](https://github.com/Shopify/shopify-api-ruby/pull/1098) Gracefully handle HTTP 204 repsonse bodies
- [#1104](https://github.com/Shopify/shopify-api-ruby/pull/1104) Allow api version overrides.

Expand Down
7 changes: 6 additions & 1 deletion lib/shopify_api/clients/http_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,12 @@ def request(request)
body: request.body.class == Hash ? T.unsafe(request.body).to_json : request.body,
), HTTParty::Response)

body = res.body.nil? || res.body.empty? ? {} : JSON.parse(res.body)
begin
body = res.body.nil? || res.body.empty? ? {} : JSON.parse(res.body)
rescue JSON::ParserError
body = res.body
nelsonwittwer marked this conversation as resolved.
Show resolved Hide resolved
end

response = HttpResponse.new(code: res.code.to_i, headers: res.headers.to_h, body: body)

if response.headers["x-shopify-api-deprecated-reason"]
Expand Down
9 changes: 9 additions & 0 deletions test/clients/http_client_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,15 @@ def test_warns_on_deprecation_header
assert_match(/#{@request.path}.*#{deprecate_reason}/, reader.gets)
end

def test_json_parser_error
stub_request(@request.http_method, "https://#{@shop}#{@base_path}/#{@request.path}")
.with(body: @request.body.to_json, query: @request.query, headers: @expected_headers)
.to_return(body: "<html>Some HTML</html>", status: 502)

error = assert_raises(ShopifyAPI::Errors::HttpResponseError) { @client.request(@request) }
assert_equal(502, error.code)
end

private

def simple_http_test(http_method)
Expand Down