Best way to check for inner exception?
I know sometimes innerException is null
So the following might fail:
repEvent.InnerException = ex.InnerException.Message;
Is there a quick ternary way to check if innerException is null or not?
Solution 1:
Great answers so far. On a similar, but different note, sometimes there is more than one level of nested exceptions. If you want to get the root exception that was originally thrown, no matter how deep, you might try this:
public static class ExceptionExtensions
{
public static Exception GetOriginalException(this Exception ex)
{
if (ex.InnerException == null) return ex;
return ex.InnerException.GetOriginalException();
}
}
And in use:
repEvent.InnerException = ex.GetOriginalException();
Solution 2:
Is this what you are looking for?
String innerMessage = (ex.InnerException != null)
? ex.InnerException.Message
: "";
Solution 3:
That's funny, I can't find anything wrong with Exception.GetBaseException()?
repEvent.InnerException = ex.GetBaseException().Message;