Aborting .DynamicInvoke delegate - catch

I call the delegate (dynamically tuned service) using:

public void CallService (Delegate service, IContext ctx)
{
    var serviceArgs = CreateServiceArguments(service, ctx);
    service.DynamicInvoke(serviceArgs);
}

At this point, I want to catch all the exceptions that have occurred in the method of the called service, however I do not want to catch any exception that has occurred due to the call to DynamicInvoke. For instance:.

  • servicedelegate throws -> DomainExceptioncatch exception
  • DynamicInvoke()throws MemberAccessException, because the delegate is a private method -> don't catch the exception, let it bubble up

Hope this is clear what I ask. How to decide if a catchy exception occurs from the DynamicInvoke call itself or from the main delegate.

Oh yes, and: I can't use the exception type to solve! It is possible that the service itself also throws a MemberAccessException because it can perform some delegate stuff ...

+4
source share
1 answer

Oh yes, and: I can't use the exception type to solve! It is possible that the service itself also throws a MemberAccessException because it can perform some delegate stuff ...

Yes, you can use an exception type to make a decision. As indicated in the documentation for Delegate.DynamicInvoke, if the called method throws an exception (any exception), it will be wrapped in TargetInvocationException. This is an exception that you can catch, and then you can look at its property InnerExceptionto see if it is an exception that you can deal with.

+3
source

All Articles