我正在使用以下方式调用委托(delegate)(动态可配置服务):
public void CallService (Delegate service, IContext ctx)
{
var serviceArgs = CreateServiceArguments(service, ctx);
service.DynamicInvoke(serviceArgs);
}
此时我想捕获在被调用的服务方法中发生的所有异常,但是,我不想捕获由于 DynamicInvoke 调用而发生的任何异常。例如:
service
委托(delegate)抛出DomainException
-> 捕获异常DynamicInvoke()
抛出MemberAccessException
因为委托(delegate)是私有(private)方法 -> 不要捕获异常,让它冒泡
我希望我的问题很清楚。如何确定捕获的异常是源自 DynamicInvoke 调用本身还是源自底层委托(delegate)。
哦,是的,而且:我不能使用异常类型来决定!服务本身也完全有可能抛出 MemberAccessException,因为它本身可以执行一些委托(delegate)操作...
最佳答案
Oh yeah, and: I cannot use the exception type to decide! It is completely possible that the service itself throws a MemberAccessException as well, because it could do some delegate stuff itself...
是的,您可以使用异常类型来决定。正如 Delegate.DynamicInvoke
的文档中提到的,如果被调用的方法抛出异常(任何异常),它将被包装在 TargetInvocationException
中。这是您可以捕获的异常,然后您可以查看其 InnerException
属性来了解它是否是您可以处理的异常。
关于c# - Delegate.DynamicInvoke - 捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954407/