From 66390c4343a9536c09d1bc47f10738daa2515d85 Mon Sep 17 00:00:00 2001 From: Doug Hughes Date: Sat, 25 Mar 2023 10:45:43 -0400 Subject: [PATCH] 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. --- .../ruby/templates/api_error.mustache | 50 ++++++++++++++----- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/swagger-config/marketing/ruby/templates/api_error.mustache b/swagger-config/marketing/ruby/templates/api_error.mustache index fbfbc32..9d13115 100644 --- a/swagger-config/marketing/ruby/templates/api_error.mustache +++ b/swagger-config/marketing/ruby/templates/api_error.mustache @@ -2,29 +2,55 @@ {{> api_info}} =end -module {{moduleName}} +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