Search code examples
c#exceptionproperties

Finding the original exception


I have an import routine that imports many values into properties of an Object. There are a lot of values to go into the Objects Properties and they can be in any order, so I use reflection to find a property then set its value. This all works really well, except if there is an exception raised by the Objects properties setter method, I don't see it.

Code excerpt:

try
{
    PropertyInfo piInstance = MBtype.GetProperty(columnlist[intColumn]);
    piInstance.SetValue(newMailbox, CurrentRow[intColumn]);
}
catch (Exception ex)
{
    HelpFunc.writeToLog($"Error: '{ex.Message}'", "Error");
}

The property thowing the intial error code is:

throw new ArgumentException($"{value} must be valid email address", value);

However, when I look at the log it not telling me the argument exception, its telling me the error is:

"Error: 'Exception has been thrown by the target of an invocation.'"

i.e. the original exception is lost.The setValue is a Net function. How can I get the original exception, so I can grab the details for logging.

Many thanks!


Solution

  • You have to check the inner Exception:

    try
    {
      PropertyInfo piInstance = MBtype.GetProperty(columnlist[intColumn]);
      piInstance.SetValue(newMailbox, CurrentRow[intColumn]);
    }
    catch (Exception ex)
    {
       HelpFunc.writeToLog($"Error: '{ex.Message}', Inner Exception: '{ex.InnerException?.Message}'", "Error");
    }
    

    I recommend always log the ToString() method of the exception, because then you have all information (including stack trace an inner exceptions).

    Online-demo: https://dotnetfiddle.net/L1msAC