Skip to content

Commit

Permalink
Improves Error Deserialization (#253)
Browse files Browse the repository at this point in the history
  • Loading branch information
jchen293 authored Apr 12, 2023
1 parent a0d978e commit ef787b4
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

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

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

Expand Down
16 changes: 15 additions & 1 deletion lib/easypost/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class EasyPost::Error < StandardError
# Initialize a new EasyPost Error
def initialize(message = nil, status = nil, code = nil, errors = nil, http_body = nil)
# message should be a string but can sometimes incorrectly come back as an array
@message = message.is_a?(Array) ? message.join(', ') : message
@message = message.is_a?(String) ? message : EasyPost::Error.traverse_json_element(message, [])
@status = status
@code = code
@errors = errors
Expand All @@ -16,6 +16,20 @@ def initialize(message = nil, status = nil, code = nil, errors = nil, http_body
super(message)
end

# Recursively traverses a JSON element to extract error messages and returns them as a comma-separated string.
def self.traverse_json_element(error_message, messages_list)
case error_message
when Hash
error_message.each_value { |value| traverse_json_element(value, messages_list) }
when Array
error_message.each { |value| traverse_json_element(value, messages_list) }
else
messages_list.push(error_message.to_s)
end

messages_list.join(', ')
end

# Convert an error to a string.
def to_s
"#{code} (#{status}): #{message} #{errors}".strip
Expand Down
29 changes: 29 additions & 0 deletions spec/error_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,34 @@

expect(error.message).to eq('Error1, Error2')
end

it 'concatenates error.message when it comes back incorrectly as a hash from the API' do
error_message = {
errors: ['bad error', 'second bad error'],
}

error = described_class.new(error_message)

expect(error.message).to eq('bad error, second bad error')
end

it 'concatenates error.message when it comes back incorrectly as an bad format from the API' do
error_message = {
message: {
errors: ['Bad format 1', 'Bad format 2'],
bad_data: [
{
first_message: 'Bad format 3',
second_message: 'Bad format 4',
thrid_message: 'Bad format 5',
},
],
},
}

error = described_class.new(error_message)

expect(error.message).to eq('Bad format 1, Bad format 2, Bad format 3, Bad format 4, Bad format 5')
end
end
end

0 comments on commit ef787b4

Please sign in to comment.