diff --git a/CHANGELOG.md b/CHANGELOG.md index 98ab67844..1c68abf00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +* Enrich 4xx errors with error message from response body [#647](https://github.com/Shopify/shopify_api/pull/647) + == Version 8.0.0 * Api Version changes [#600](https://github.com/Shopify/shopify_api/pull/600) diff --git a/lib/shopify_api.rb b/lib/shopify_api.rb index 6a5eb0e62..108242c59 100644 --- a/lib/shopify_api.rb +++ b/lib/shopify_api.rb @@ -20,6 +20,7 @@ module ShopifyAPI require 'shopify_api/countable' require 'shopify_api/resources' require 'shopify_api/session' +require 'shopify_api/message_enricher' require 'shopify_api/connection' require 'shopify_api/pagination_link_headers' diff --git a/lib/shopify_api/connection.rb b/lib/shopify_api/connection.rb index 2175f965c..b7b655ce6 100644 --- a/lib/shopify_api/connection.rb +++ b/lib/shopify_api/connection.rb @@ -4,7 +4,7 @@ class Connection < ActiveResource::Connection module ResponseCapture def handle_response(response) - @response = super + @response = super(ShopifyAPI::MessageEnricher.new(response)) end end diff --git a/lib/shopify_api/message_enricher.rb b/lib/shopify_api/message_enricher.rb new file mode 100644 index 000000000..fbfe96c99 --- /dev/null +++ b/lib/shopify_api/message_enricher.rb @@ -0,0 +1,17 @@ +module ShopifyAPI + class MessageEnricher < SimpleDelegator + def message + return super unless (400...500).include?(code.to_i) + + @_cached_message ||= begin + detailed_error = begin + JSON.parse(body)['error'].to_s + rescue JSON::ParserError + nil + end + + detailed_error.present? ? "#{super} (#{detailed_error})" : super + end + end + end +end diff --git a/test/message_enricher_test.rb b/test/message_enricher_test.rb new file mode 100644 index 000000000..3f8b37679 --- /dev/null +++ b/test/message_enricher_test.rb @@ -0,0 +1,33 @@ +require 'test_helper' + +class MessageEnricherTest < Test::Unit::TestCase + + def test_enriches_initial_message_when_body_is_passed + response = enriched_response(422, 'InitialMessage', { error: 'My Error' }) + + assert_equal 'InitialMessage (My Error)', response.message + end + + def test_returns_initial_message_when_code_is_200 + response = enriched_response(200, 'InitialMessage', { result: 'Success' }) + + assert_equal 'InitialMessage', response.message + end + + def test_returns_initial_message_when_body_cant_be_parsed + response = enriched_response(422, 'InitialMessage', 'not a json') + + assert_equal 'InitialMessage', response.message + end + + private + + def enriched_response(code, message, body) + mock_response = + Struct + .new(:code, :message, :body) + .new(code.to_s, message.to_s, body.to_json) + + ShopifyAPI::MessageEnricher.new(mock_response) + end +end