I have used a DotNet function to read XmlNodes from an XML file, however sometimes we get sent an XML file which doesn't contain a DateTime attribute for a certain node..
When I run my CodeUnit, I get an error due to there being no node to read and the file instantly gets discarded in the Error folder -> is there a way of doing either a Try / Catch or checking if the node is not empty / null?
XmlInBound.LocationDateType := xmlNode.SelectSingleNode('DateTime/@DateType').Value();
The above errors out when there is no attribute to read. I am using Dynamics-Nav 2013 R2.
There is a number of options you could go with.
First, if there are no nodes you search for, SelectSingleNode returns NULL. All you have to do is check it for ISNULL before trying to call Value() function:
xmlSubNode := xmlNode.SelectSingleNode('DateTime/@DateType');
IF NOT ISNULL(xmlSubNode) THEN
XmlInBound.LocationDateType := xmlSubNode.Value();
You may also want to examine standard codeunit 6224 XML DOM Management, which contains number of wrapper functions for XML parsing. There are functions FindNodeXXX that you could use instead of writing your own code.
If you want to implement try..catch in Dynamics NAV 2013 R2, the way to do it is via IF CODEUNIT.RUN THEN construct. You will need to create a new codeunit which has all the error-possible code in OnRun trigger, pass necessary parameters to it and then run it inside IF statement:
HandleCodeunit.SetParameters(xmlNode,...);
IF HandleCodeunit.RUN THEN BEGIN
HandleCodeunit.GetResults(...);
END ELSE BEGIN
// Handle error
MESSAGE(GETLASTERRORTEXT);
MESSAGE(GETLASTERRORCALLSTACK);
MESSAGE(FORMAT(GETLASTERROROBJECT));
END;
Please note, that you should not be inside of a write transaction to be able to use IF RUN statement.