myob-oss / AccountRight_Live_API_.Net_SDK

This is the repo for the MYOB AccountRight Live .Net SDK
MIT License
23 stars 43 forks source link

Better Reporting of Errors on 400 Errors #279

Open JasonTaylorAcronym opened 2 days ago

JasonTaylorAcronym commented 2 days ago

Currently the only message we get in the thrown exception is

Encountered a validation error (https://arl2.api.myob.com/accountright/b7259c7c-a109-4013-a6e2-9be6410ab300/Sale/Invoice/Service/?returnBody=true)

But I can see in the response body what the actual issue is

{
  "Errors": [
    {
      "Name": "CustomerNotFound",
      "Message": "The Customer with UID of '511d425d-a306-4e19-add4-de842086444a' cannot be found.",
      "AdditionalDetails": "Customer.UID",
      "ErrorCode": 11003,
      "Severity": "Error",
      "LearnMore": null
    }
  ],
  "Information": "Warning, error messages have not been finalised in this release and may change"
}

Would be much more helpful to the end user if we could display the actual error messages

I tired accessing the response stream but its been disposed already

            try
            {
                myobInvoice = _myobService.InsertInvoice(myobInvoice);
            }
            catch (Exception ex)
            {
                if (ex.InnerException is WebException)
                {
                    var webException = ex.InnerException as WebException;

                    var stream = webException.Response.GetResponseStream();

                    using (var streamReader = new StreamReader(stream)) // throws exception stream is not readable
                    {
                        var content = streamReader.ReadToEnd();
                    }
                }
JasonTaylorAcronym commented 2 days ago

This PR would help https://github.com/myob-oss/AccountRight_Live_API_.Net_SDK/pull/276

dkarzon commented 1 day ago

@JasonTaylorAcronym I may have an answer for this one. If you catch the exception type ApiCommunicationException here it has an Errors property that gets populated with that data from the request. Make sure you null check the Errors property first 😉

But yes, my PR will also help a bit with this because it will allow you to better handle these errors yourself.

JasonTaylorAcronym commented 9 hours ago

@dkarzon Thanks for that, it does indeed work

            try
            {
                myobInvoice = _myobService.InsertInvoice(myobInvoice);
            }
            catch (ApiCommunicationException ex)
            {
                if (ex.Errors?.Any() == true)
                {
                    throw new Exception(ex.Errors.First().Message, ex);
                }

                throw ex;
            }