Catch CLR errors in X++ in Dynamics 365 for Operations

Although there are useful posts out there on catching CLR errors in X++ for older versions of Dynamics AX, as of this writing, I couldn’t find one that address the current version. It took me a little experimentation and trial-and-error to figure out how to do it; in particular, to actually return a useful error message, instead of just a generic CLR error. Below is the pattern I use. For simplicity, I’m leaving out some of the other types of CATCH you might use, as well as other detail irrelevant to the pattern.

As usual, I would greatly appreciate comments on whether this works for you, and if you know of any improvements.

System.Exception e;
InteropPermission interopPermission;
try
{
interopPermission = new InteropPermission(InteropKind::ComInterop);
interopPermission.assert();
// REST OF CODE THAT MIGHT GENERATE A CLR ERROR
}
catch (Exception::CLRError)
{
e = CLRInterop::getLastException();
if (e != null)
{
e = e.InnerException;
throw error(e.ToString());
//…or whatever you want to do with that error text
}
else
{
throw error("null CLR error caught blah blah blah");
}
}
catch
{
//other error handling
}
finally
{
CodeAccessPermission::revertAssert();
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s