调用的目标(MethodBase.Invoke方法)已引发异常 [英] Exception has been thrown by the target of an invocation (MethodBase.Invoke Method)
问题描述
我想捕获在用invoke方法调用的方法中引发的异常。
I want to catch the exceptions that are thrown in methods called with invoke method.
public void TestMethod()
{
try
{
method.Invoke(commandHandler, new[] { newCommand });
}
catch(Exception e)
{
ExceptionService.SendException(e);
}
}
方法。调用调用以下方法:
method.Invoke calls the following method:
public void Register(/*parameters*/)
{
if(test_condition())
throw new CustomException("Exception Message");
}
问题是当我在CustomMethod中捕获CustomException时,e catch语句上的变量的类型不是CustomException。它具有以下消息:调用的目标已引发异常。
The problem is that when I catch the CustomException, in the TestMethod, the e variable on the catch statement has NOT the type CustomException. It has the following message: "Exception has been thrown by the target of an invocation".
我想捕获已引发的异常(这是CustomException),并将其传递给ExceptionService机制。
I want to catch the exception that has been raised (which is CustomException), and pass it to the ExceptionService mechanism.
我在做什么错了?
推荐答案
是的,你是通过反射重新调用该方法。因此,根据文档,< a href = https://msdn.microsoft.com/zh-cn/library/system.reflection.targetinvocationexception(v=vs.110).aspx rel = noreferrer> TargetInvocationException 如果目标方法抛出异常,将抛出code> 。
Yes, you're calling the method via reflection. So as per the documentation, a TargetInvocationException
will be thrown if the target method throws an exception.
只需使用 InnerException
属性
Just use the InnerException
property to obtain - and potentially throw - the original exception.
因此,例如:
try
{
method.Invoke(commandHandler, new[] { newCommand });
}
catch (TargetInvocationException e)
{
ExceptionService.SendException(e.InnerException);
}
这篇关于调用的目标(MethodBase.Invoke方法)已引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!