Duplicate of: In C#, how can I rethrow InnerException without losing stack trace?
I have some operations that I invoke asynchronously on a background thread. Sometimes,
There is a way of "resetting" the stack trace on an exception by using the internal mechanism that is used to preserve server side stack traces when using remoting, but it is horrible:
try
{
// some code that throws an exception...
}
catch (Exception exception)
{
FieldInfo remoteStackTraceString = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
remoteStackTraceString.SetValue(exception, exception.StackTrace);
throw exception;
}
This puts the original stack trace in the _remoteStackTraceString
field of the exception, which gets concatenated to the newly reset stack trace when the exception is re-thrown.
This is really a horrible hack, but it does achieve what you want. You are tinkering inside the System.Exception
class though so this method may therefore break in subsequent releases of the framework.