-
Notifications
You must be signed in to change notification settings - Fork 474
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Enrich 4xx error message with error text in response.body
- Loading branch information
Showing
4 changed files
with
52 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |