Skip to content

Commit ef787b4

Browse files
authored
Improves Error Deserialization (#253)
1 parent a0d978e commit ef787b4

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
- Drops support for Ruby 2.5
66
- Bumps all dev dependencies
7+
- Improves Error Deserialization to dynamically handle edge cases that have a bad format
78

89
## v4.13.0 (2023-04-04)
910

lib/easypost/error.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ class EasyPost::Error < StandardError
77
# Initialize a new EasyPost Error
88
def initialize(message = nil, status = nil, code = nil, errors = nil, http_body = nil)
99
# message should be a string but can sometimes incorrectly come back as an array
10-
@message = message.is_a?(Array) ? message.join(', ') : message
10+
@message = message.is_a?(String) ? message : EasyPost::Error.traverse_json_element(message, [])
1111
@status = status
1212
@code = code
1313
@errors = errors
@@ -16,6 +16,20 @@ def initialize(message = nil, status = nil, code = nil, errors = nil, http_body
1616
super(message)
1717
end
1818

19+
# Recursively traverses a JSON element to extract error messages and returns them as a comma-separated string.
20+
def self.traverse_json_element(error_message, messages_list)
21+
case error_message
22+
when Hash
23+
error_message.each_value { |value| traverse_json_element(value, messages_list) }
24+
when Array
25+
error_message.each { |value| traverse_json_element(value, messages_list) }
26+
else
27+
messages_list.push(error_message.to_s)
28+
end
29+
30+
messages_list.join(', ')
31+
end
32+
1933
# Convert an error to a string.
2034
def to_s
2135
"#{code} (#{status}): #{message} #{errors}".strip

spec/error_spec.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,34 @@
3333

3434
expect(error.message).to eq('Error1, Error2')
3535
end
36+
37+
it 'concatenates error.message when it comes back incorrectly as a hash from the API' do
38+
error_message = {
39+
errors: ['bad error', 'second bad error'],
40+
}
41+
42+
error = described_class.new(error_message)
43+
44+
expect(error.message).to eq('bad error, second bad error')
45+
end
46+
47+
it 'concatenates error.message when it comes back incorrectly as an bad format from the API' do
48+
error_message = {
49+
message: {
50+
errors: ['Bad format 1', 'Bad format 2'],
51+
bad_data: [
52+
{
53+
first_message: 'Bad format 3',
54+
second_message: 'Bad format 4',
55+
thrid_message: 'Bad format 5',
56+
},
57+
],
58+
},
59+
}
60+
61+
error = described_class.new(error_message)
62+
63+
expect(error.message).to eq('Bad format 1, Bad format 2, Bad format 3, Bad format 4, Bad format 5')
64+
end
3665
end
3766
end

0 commit comments

Comments
 (0)