require 'amsi/error/bad_request' module Amsi module Validator # Ensure there are no errors in the wrapped contents of the body. # # This validator works on responses that have the following format: # # # # # # <InternetTrafficResponse><webservice>Leasing</webservice><webmethod>GetPropertyResidents</webmethod><Error><ErrorCode>1</ErrorCode><ErrorDescription>Validation of user credentials failed.</ErrorDescription></Error></InternetTrafficResponse> # # # class RequestErrors # @param response [Hash] the XML response parsed into a # Hash def initialize(response) @response = response end # @raise [Amsi::Error::BadRequest] if the response has an error # node in the contents def validate! return unless error? raise Amsi::Error::BadRequest, [error] end private attr_reader :response def error_contents body = response['soap:Envelope']['soap:Body'] response_key = body.keys.detect { |key| key !~ /^xmlns/ } contents_response = body[response_key] result_key = contents_response.keys.grep(/Result$/).first escaped_result = contents_response[result_key] parsed_result = MultiXml.parse(escaped_result) parsed_result['InternetTrafficResponse'] end def error? error_contents end def error error = error_contents['Error'] Struct.new(:message, :error_code).new( error['ErrorDescription'], error['ErrorCode'] ) end end end end