Browse Source

Take into account semantical 'errors' key in JSON body for 422 responses

According to the documentation
https://help.shopify.com/en/api/getting-started/response-status-codes:
  422 Unprocessable Entity
  The request body was well-formed but contains semantical errors.
  The response body will provide more details in the errors or
  error parameters.

Hence, there is no point in enriching messages for any response but one
with 422 code.
There might be `errors` key containing array of error messages. This is
handled as well
Volodymyr Byno 5 years ago
parent
commit
1b630545a0
3 changed files with 22 additions and 2 deletions
  1. 2 0
      CHANGELOG.md
  2. 7 1
      lib/shopify_api/message_enricher.rb
  3. 13 1
      test/message_enricher_test.rb

+ 2 - 0
CHANGELOG.md

@@ -1,3 +1,5 @@
+* Take into account "errors" messages from response body [#677](https://github.com/Shopify/shopify_api/pull/677)
+
 == Version 9.0.0
 
 * Breaking change: Improved GraphQL client [#672](https://github.com/Shopify/shopify_api/pull/672). See the [client docs](docs/graphql.md) for usage and a migration guide.

+ 7 - 1
lib/shopify_api/message_enricher.rb

@@ -5,7 +5,13 @@ module ShopifyAPI
 
       @_cached_message ||= begin
         detailed_error = begin
-          JSON.parse(body)['error'].to_s
+          parsed_body = JSON.parse(body)
+
+          if parsed_body['error']
+            parsed_body['error'].to_s
+          elsif parsed_body['errors']
+            Array(parsed_body['errors']).join('; ')
+          end
         rescue JSON::ParserError
           nil
         end

+ 13 - 1
test/message_enricher_test.rb

@@ -2,12 +2,24 @@ require 'test_helper'
 
 class MessageEnricherTest < Test::Unit::TestCase
 
-  def test_enriches_initial_message_when_body_is_passed
+  def test_enriches_initial_message_when_body_contains_error
     response = enriched_response(422, 'InitialMessage', { error: 'My Error' })
 
     assert_equal 'InitialMessage (My Error)', response.message
   end
 
+  def test_enriches_initial_message_when_body_contains_errors_array
+    response = enriched_response(422, 'InitialMessage', { errors: ['My Error1', 'My Error2'] })
+
+    assert_equal 'InitialMessage (My Error1; My Error2)', response.message
+  end
+
+  def test_enriches_initial_message_when_body_contains_errors_single_value
+    response = enriched_response(422, 'InitialMessage', { errors: 'My Error1' })
+
+    assert_equal 'InitialMessage (My Error1)', response.message
+  end
+
   def test_returns_initial_message_when_code_is_200
     response = enriched_response(200, 'InitialMessage', { result: 'Success' })