Skip to content

Commit eef4639

Browse files
authored
Merge pull request #326 from dhughes/improve_ruby_gem_error_handling
Parse ruby error response body and add attributes
2 parents 521c919 + 66390c4 commit eef4639

File tree

1 file changed

+38
-12
lines changed

1 file changed

+38
-12
lines changed

swagger-config/marketing/ruby/templates/api_error.mustache

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,55 @@
22
{{> api_info}}
33
=end
44

5-
module {{moduleName}}
5+
require 'json'
6+
7+
module MailchimpMarketing
68
class ApiError < StandardError
79
attr_reader :status, :type, :title, :detail, :instance, :errors
810

11+
attr_reader :response_headers, :response_body
12+
913
# Usage examples:
1014
# ApiError.new
1115
# ApiError.new("message")
1216
# ApiError.new(:status => 500, :response_headers => {}, :response_body => "")
1317
# ApiError.new(:status => 404, :message => "Not Found")
14-
def initialize(arg = nil)
15-
if arg.is_a? Hash
16-
if arg.key?(:message) || arg.key?('message')
17-
super(arg[:message] || arg['message'])
18-
else
19-
super arg
20-
end
18+
def initialize(arguments = nil)
19+
@arguments = arguments
20+
return super(@arguments) unless @arguments.is_a?(Hash)
21+
22+
@arguments.transform_keys!(&:to_sym)
2123

22-
arg.each do |k, v|
23-
instance_variable_set "@#{k}", v
24+
expand_response_body_into_arguments
25+
26+
super(@arguments[:title] || @arguments[:message])
27+
28+
@arguments.each do |key, value|
29+
instance_variable_set("@#{key}", value)
30+
end
31+
end
32+
33+
private
34+
35+
def expand_response_body_into_arguments
36+
@arguments.merge!(parsed_response_body) unless parsed_response_body.nil?
37+
end
38+
39+
def parsed_response_body
40+
@parsed_response_body ||= begin
41+
parsed_response_body = JSON.parse(@arguments[:response_body]).transform_keys(&:to_sym)
42+
43+
if parsed_response_body[:errors].is_a?(Array)
44+
parsed_response_body[:errors].map do |error|
45+
error.transform_keys!(&:to_sym)
46+
end
2447
end
25-
else
26-
super arg
48+
49+
parsed_response_body
50+
rescue
51+
nil
2752
end
2853
end
54+
2955
end
3056
end

0 commit comments

Comments
 (0)