How to rethrow the inner exception of a TargetInvocationException without losing the stack trace

后端 未结 3 2145
花落未央
花落未央 2020-12-05 14:46

I have many methods which are calling using Delegate.DynamicInvoke. Some of these methods make database calls and I would like to have the ability to catch a

3条回答
  •  独厮守ぢ
    2020-12-05 14:52

    If you just want to re-throw an inner exception preserving its stack trace, you can do it with a method like this:

    public static void Rethrow(this Exception ex)
    {
      typeof(Exception).GetMethod("PrepForRemoting",
          BindingFlags.NonPublic | BindingFlags.Instance)
          .Invoke(ex, new object[0]);
      throw ex;
    }
    

    This technique is used by Rx (and is exposed by them as an extension method Exception.PrepareForRethrow) and is also used by the Async CTP by its automatic-unwrapping system (without a publicly-exposed API).

    Note, however, that this technique is technically unsupported. Hopefully Microsoft will add an official API for this in the future. A suggestion has been opened on Microsoft Connect if you would like to vote for it.

    Update: An official API has been added to .NET 4.5: ExceptionDispatchInfo.

提交回复
热议问题