From f5908baaec266efff24467394b4f021ef184073c Mon Sep 17 00:00:00 2001 From: Tim Diggins Date: Tue, 19 Oct 2021 16:26:17 +0100 Subject: [PATCH] add errors to the record if ApiException is raised. This does a very basic fix to #538 by parsing the thrown ApiException. This won't help if an ApiException isn't thrown (unexpected error). It also feels rather ugly having to catch and re-raise, but any other change would be a very significant refactor. --- lib/xeroizer/record/base.rb | 6 ++++++ test/unit/record/base_test.rb | 20 +++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/xeroizer/record/base.rb b/lib/xeroizer/record/base.rb index a0534a5fb..cdf424fe7 100644 --- a/lib/xeroizer/record/base.rb +++ b/lib/xeroizer/record/base.rb @@ -121,6 +121,12 @@ def save! end saved! + rescue ApiException => e + valid? # we are calling this to populate with known errors, but also set up @errors object + e.validation_errors.each do |error| + errors << [:base, error] + end + raise end def saved! diff --git a/test/unit/record/base_test.rb b/test/unit/record/base_test.rb index f2cdcd111..62cd161a3 100644 --- a/test/unit/record/base_test.rb +++ b/test/unit/record/base_test.rb @@ -135,6 +135,11 @@ class Xeroizer::Record::ExampleRecordClassModel < Xeroizer::Record::BaseModel; e context 'api error received' do setup do response = get_file_as_string('api_exception.xml') + + # XeroGenericApplication API Exceptions *claim* to be UTF-16 encoded, but are not + # @see http_response.rb Xeroizer::XmlErrorResponse#raise_bad_request! + response.gsub! '', '' + doc = Nokogiri::XML(response) exception = Xeroizer::ApiException.new(doc.root.xpath("Type").text, doc.root.xpath("Message").text, @@ -142,7 +147,6 @@ class Xeroizer::Record::ExampleRecordClassModel < Xeroizer::Record::BaseModel; e doc, '') - @contact.stubs(:valid?).returns(true) @contact.stubs(:create).raises(exception) @contact.stubs(:update).raises(exception) end @@ -170,6 +174,20 @@ class Xeroizer::Record::ExampleRecordClassModel < Xeroizer::Record::BaseModel; e @contact.stubs(:new_record?).returns(false) assert_equal(false, @contact.save) end + + must 'set errors creating records with #save' do + @contact.stubs(:new_record?).returns(true) + @contact.save + assert_equal([[:base, "Users Organisation is not subscribed to currency NZD"]], @contact.errors) + end + + must 'set errors updating records with #save!' do + @contact.stubs(:new_record?).returns(false) + assert_raise(Xeroizer::ApiException) do + @contact.save! + end + assert_equal([[:base, "Users Organisation is not subscribed to currency NZD"]], @contact.errors) + end end end end