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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } |