In Microsoft Dynamics AX, when your X++ code calls .NET framework methods it is important that your code be designed to handle exceptions. When your code catches exceptions it can relay valuable diagnostic information to the user.
The following X++ code sample demonstrates how to handle exceptions that are thrown from .NET methods
// X++
static void JobCreateEventLog(Args _args)
{
#define.LogSource("Dynamics AX")
#define.LogName("Dynamics AX Log")
System.Exception ex;
System.Diagnostics.EventLog eventLog;
;
try
{
// Create the log if it does not already exist.
if (!System.Diagnostics.EventLog::SourceExists(#LogSource))
{
System.Diagnostics.EventLog::CreateEventSource(#LogSource, #LogName);
}
// Next line is an intentional bug for this demonstration of CLR exceptions.
// It causes an exception due to a name duplication.
System.Diagnostics.EventLog::CreateEventSource(#LogSource, #LogName);
// Write to this newly created log source, if the process gets this far.
eventLog = new System.Diagnostics.EventLog();
eventLog.set_Source(#LogSource);
eventLog.WriteEntry
("The exception should prevent this line from appearing in the Windows event viewer.",
System.Diagnostics.EventLogEntryType::Warning
);
}
catch (Exception::CLRError)
{
ex = ClrInterop::getLastException();
if (ex != null)
{
ex = ex.get_InnerException();
if (ex != null)
{
error(ex.ToString());
}
}
}
// Clean up.
System.Diagnostics.EventLog::DeleteEventSource(#LogSource, #LogName);
}
/*** Messages displayed in the Infolog:
System.ArgumentException: Source Dynamics AX already exists on the local computer.
at System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData)
at System.Diagnostics.EventLog.CreateEventSource(String source, String logName)
***/