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

后端 未结 3 2148
花落未央
花落未央 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:54

    You need to keep in mind why .NET wraps the exception with a TargetInvocationException instead of just letting the original exception through. There's a really good reason for that, it isn't obvious where the real reason for the exception came from. Was it because the DynamicInvoke() call is borked? Not unlikely, there's nothing that the compiler can do to ensure that the correct arguments were passed. Or did the invoked target method throw all by itself?

    You need to know both to judge the real reason for the exception. Intentionally hiding the TargetInvocationException is going to give you a hard time to diagnose the source of the trouble if it was indeed a problem with the DynamicInvoke() call. Avoid doing this.

提交回复
热议问题