web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Unanswered

Error handling for web responses in D365 FO x++

(2) ShareShare
ReportReport
Posted on by 44
Hi community members,
 
I am consuming a Json based API in D365 FO x++. I am using this piece of code while posting the data. It is working fine but the issue when the web response got some errors it does not come into the any catch blocks of the code. I want to show the error message to the user for any bad request like missing items fields but the system only throws the "The error has been thrown by the target of an exception." I have tried many error handling techniques but no solution. Can anyone please guide me what I can try so that the debugger might enter into the catch block of the code.
 
I can see the errors in the postman.
 
Thanks
 
    public void sendFiscal(str _json, CustInvoiceJour _custInvoiceJour)
    {
        str UserAuthToken = 'Authorization';
        str apiKey = 'X-Api-Key';
        str scId = 'X-SdcId';
        CustParameters custParameters = CustParameters::find();
        str apiURL =  custParameters.AXPApiURL; 

        System.Net.HttpWebRequest request;
        System.Net.HttpWebResponse response;
        CLRObject clrObj;
        System.Exception ex;
        System.IO.StreamWriter streamWriter;
        System.Net.WebHeaderCollection httpHeader;
        System.IO.Stream            responseStream;
        System.IO.StreamReader      reader;
        System.ArgumentException    argEx;
        System.Net.WebException     webException;
        str serviceResponse;
        custInvoiceJour custInvoiceJour;
        List listData = new List(Types::Class);
        ListEnumerator listEnumerator;
      
        try
        {
            new InteropPermission(InteropKind::ClrInterop).assert();
            
            httpHeader = new System.Net.WebHeaderCollection();
            httpHeader.Add(apiKey, custParameters.AXPApiKey);
            httpHeader.Add(scId,custParameters.AXPSdcId);

            clrObj = System.Net.WebRequest::Create(apiURL);
            request = clrObj;
            request.set_Headers(httpHeader);
            request.Method = 'POST';
            request.ContentType = 'application/json';

            streamWriter = new System.IO.StreamWriter(request.GetRequestStream());
            streamWriter.Write(_json);
            streamWriter.Flush();
            streamWriter.Close();

            response = request.GetResponse();
            responseStream = response.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream);
    
            serviceResponse = reader.ReadToEnd();
            
            if (response.StatusDescription == 'OK')
            {
                info( strFmt("%1",serviceResponse));
                headerResponse = FormJSONSerializer::deserializeObject(classNum(),serviceResponse);
                info( strFmt("%1",headerResponse.parmInternalData() ));
   
            }
            
            else
            {
                throw error("Something went wrong");
            }
        }

        catch (webException)
        {
            // Handle WebException for error response
            if (webException.get_Response() != null)
            {
                System.Net.HttpWebResponse httpWebResponse;
                Notes                      responseString;
                System.IO.Stream           stream;
                System.IO.StreamReader     streamReader;

                // Get error response stream
                httpWebResponse = webException.get_Response() as System.Net.HttpWebResponse;
                stream = httpWebResponse.GetResponseStream();
                streamReader = new System.IO.StreamReader(stream);
                responseString = streamReader.ReadToEnd();

                // Log the error response body (usually in JSON format)
                error(strFmt("Error Response (JSON): %1", responseString));

                // Close resources
                streamReader.Close();
                stream.Close();
                httpWebResponse.Close();
            }
            else
            {
                // Log the exception message if no response
                error(strFmt("WebException occurred: %1", webException.get_Message()));
            }
        }
        catch (Exception::CLRError)
        {
            ex = CLRInterop::getLastException().GetBaseException();
            throw error(ex.get_Message());
        }
        catch (ex)
        {
            ex = CLRInterop::getLastException().GetBaseException();
            throw error(ex.get_Message());
        }
        catch
        {
            error("Checking!");
        }
    }
  
Categories:
I have the same question (0)
  • Bharani Preetham Peraka Profile Picture
    3,634 Moderator on at
    Try adding ExceptionType error and check.
  • Martin Dráb Profile Picture
    237,805 Most Valuable Professional on at
    Please debug your code and tell us what happens there. Maybe you're getting a response and you need to analyze data in serviceResponse variable. Or maybe your catch blocks are completely ignored because the code executes inside a database transaction.
     
    Just by the way, you can simplify your code by declaring variables locally where needed. In Dynamics AX, you had to declare variables on the top of a method, but it's not true anymore in F&O.
  • Layan Jwei Profile Picture
    8,097 Super User 2025 Season 2 on at
    Hi,

    can you let us know at which line of code does it fail exactly?
  • Ammad majid Profile Picture
    44 on at
    Hi Layan,
     
    It is failing on the below line of code. After that it must go to the catch block but it is not entering into any catch block.
     
    response = request.GetResponse();
  • Martin Dráb Profile Picture
    237,805 Most Valuable Professional on at
    As I mentioned a month ago, your catch block may be ignored because it's inside a transaction. Use the debugger, stop at the line with GetResponse() and check the value of TtsLevel in the Autos window.
     
     
    If it's not zero, you have your answer.
  • Ammad majid Profile Picture
    44 on at
    Hi Martin,
     
    Thanks for your reply. I will check the value. But lets assume the value is not zero and we have this thing inside a transaction so what can I do to resolve this issue. I need the code debugger to get into the catch block. Is there some workaround?
  • Ammad majid Profile Picture
    44 on at
    Hi Martin,
     
    On debugging I can verify the Ttslevel = 3. How can I make the code to come in the catch block?
     
    My task is to show the error message to user and the message I placed is in the catch block. So what can I do to achieve it?
     
    Regards,
    Ammad
  • Martin Dráb Profile Picture
    237,805 Most Valuable Professional on at
    Your current solution simply can't work.
     
    You'd have to place the catch block outside the transaction, i.e. the top-most transaction needs to be started inside your try block, not the other way around. Your next step is finding where the first transaction starts.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 664 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 522 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 303 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans