How can I rethrow an Inner Exception while maintaining the stack trace generated so far?

后端 未结 8 1930
春和景丽
春和景丽 2021-01-31 05:03

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,

相关标签:
8条回答
  • 2021-01-31 06:02

    It is possible with .net 4.5:

    catch(Exception e)
    {
       ExceptionDispatchInfo.Capture(e.InnerException).Throw();
    }
    
    0 讨论(0)
  • 2021-01-31 06:05

    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.

    0 讨论(0)
提交回复
热议问题