Browse Source

Enrich 4xx error message with error text in response.body

Volodymyr Byno 5 years ago
parent
commit
d2bd6d28c4

+ 2 - 0
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)

+ 1 - 0
lib/shopify_api.rb

@@ -20,6 +20,7 @@ require 'shopify_api/metafields'
 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'
 

+ 1 - 1
lib/shopify_api/connection.rb

@@ -4,7 +4,7 @@ module ShopifyAPI
 
     module ResponseCapture
       def handle_response(response)
-        @response = super
+        @response = super(ShopifyAPI::MessageEnricher.new(response))
       end
     end
 

+ 17 - 0
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

+ 33 - 0
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