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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…