Wednesday, July 30, 2014

Catching errors vs CLR errors via try...catch

When utilizing try catch's within CLR objects (.NET extensions) I noticed that if you do not specifiy the type of catch it is then they will always go to the same catch. So the following occurs

try
{
 //do something in X++
 throw error("exit out of code because of missing data");
}
catch
{
 //the throw error lands the code logic here which is correct
}


However if I want to catch a clr error and display it, but if I throw an AX error I want some logic to occur or just ignore everything and stop the issue is they both end up at the same CLR error location. The problem is when you run the throw error it also ends up being handled like a CLR error which it is not because nothing was defined for the catch. Which is shown below


try
{
  System.Exception errorMsg;
 //do something in X++ that references a .net object (CLR)
 throw error("exit out of code because of missing data");
}
catch(Exception::CLRError)
{
 //a clr error ends here
 //but the throw error also lands here thus displaying an error message to the user that is not true
       
 errorMsg = CLRInterop::getLastException();
 info(netExcepn.ToString());
}


So in order to handle CLR errors vs AX errors cleanly you would need to do the following


try
{
  System.Exception errorMsg;
 //do something in X++ that references a .net object (CLR)
 throw error("exit out of code because of missing data");
}
catch (Exception::Error)
{
 //ax thrown errors get handled here
 return false;
}
catch(Exception::CLRError)
{
 //a clr error ends here
       
 errorMsg = CLRInterop::getLastException();
 info(netExcepn.ToString());
}



You can also do the following and it works just the same


try
{
  System.Exception errorMsg;
 //do something in X++ that references a .net object (CLR)
 throw error("exit out of code because of missing data");
}
catch(Exception::CLRError)
{
 //a clr error ends here
       
 errorMsg = CLRInterop::getLastException();
 info(netExcepn.ToString());
}
catch
{
 //ax thrown errors get handled here
 return false;
}

No comments:

Post a Comment