Skip to content

Commit

Permalink
Parse response_body and flesh out attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
dhughes committed Jun 26, 2021
1 parent 99e020b commit 99143cc
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions lib/MailchimpMarketing/api_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,40 @@
=end

require 'json'

module MailchimpMarketing
class ApiError < StandardError
attr_reader :status, :type, :title, :detail, :instance, :errors

attr_reader :response_headers, :response_body
attr_reader :response_headers, :response_body, :parsed_response_body

# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:status => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:status => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
if arg.key?(:message) || arg.key?('message')
super(arg[:message] || arg['message'])
if arg.is_a?(Hash)
arg.transform_keys!(&:to_sym)

if arg.key?(:message)
super(arg[:message])
elsif arg.key?(:response_body)
@parsed_response_body = JSON.parse(arg[:response_body] ).transform_keys!(&:to_sym)
super parsed_response_body[:title]
else
super arg
end

arg.each do |k, v|
instance_variable_set "@#{k}", v
if parsed_response_body && parsed_response_body[:errors].is_a?(Array)
parsed_response_body[:errors].map do |error|
error.transform_keys!(&:to_sym)
end
end

arg.merge(parsed_response_body || {}).each do |k, v|
instance_variable_set("@#{k}", v)
end
else
super arg
Expand Down

0 comments on commit 99143cc

Please sign in to comment.