Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add attr_reader for response data to MailchimpMarketing::ApiError #5

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,5 @@ build/

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc

.idea
2 changes: 1 addition & 1 deletion lib/MailchimpMarketing/api_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def call_api(http_method, path, opts = {})
res = nil
case http_method.to_sym.downcase
when :post, :put, :patch, :delete
res = conn.request(:method => http_method, :body => opts[:body])
res = conn.request(:method => http_method, :body => opts[:body], :query => opts[:query_params])
when :get
res = conn.get(:query => opts[:query_params])
end
Expand Down
48 changes: 37 additions & 11 deletions lib/MailchimpMarketing/api_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,55 @@

=end

require 'json'

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

attr_reader :response_headers, :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'])
else
super arg
end
def initialize(arguments = nil)
@arguments = arguments
return super(@arguments) unless @arguments.is_a?(Hash)

@arguments.transform_keys!(&:to_sym)

arg.each do |k, v|
instance_variable_set "@#{k}", v
expand_response_body_into_arguments

super(@arguments[:title] || @arguments[:message])

@arguments.each do |key, value|
instance_variable_set("@#{key}", value)
end
end

private

def expand_response_body_into_arguments
@arguments.merge!(parsed_response_body) unless parsed_response_body.nil?
end

def parsed_response_body
@parsed_response_body ||= begin
parsed_response_body = JSON.parse(@arguments[:response_body]).transform_keys(&:to_sym)

if parsed_response_body[:errors].is_a?(Array)
parsed_response_body[:errors].map do |error|
error.transform_keys!(&:to_sym)
end
end
else
super arg

parsed_response_body
rescue
nil
end
end

end
end