Skip to content

Commit 66390c4

Browse files
committed
Parse ruby error response body and add attributes
This commit updates the ApiError class in the generated Ruby gem. The class has been updated to not pass hash arguments directly to the StandardError constructor. Only a possible title or message hash attribute is passed to StandardError. This prevents Ruby from stringifying a hash and using that as the error message, which is both ugly and unusable.
1 parent f6bc606 commit 66390c4

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)