调用的目标抛出了异常(MethodBase.Invoke方法)

时间:2015-09-23 13:52:16

标签: c# exception reflection invoke

我想捕获在使用invoke方法调用的方法中抛出的异常。

public void TestMethod()
{
   try     
   {
       method.Invoke(commandHandler, new[] { newCommand });
   }
   catch(Exception e)
   {     
       ExceptionService.SendException(e);
   }
}

method.Invoke调用以下方法:

public void Register(/*parameters*/)
{
     if(test_condition())
          throw new CustomException("Exception Message");
}

问题是当我捕获CustomException时,在TestMethod中,catch语句中的e变量没有类型CustomException。它有以下消息:"调用目标抛出了异常"。

我想捕获已引发的异常(即CustomException),并将其传递给ExceptionService机制。

我做错了什么?

1 个答案:

答案 0 :(得分:9)

是的,您通过反思调用该方法。因此,根据the documentation,如果目标方法抛出异常,则会抛出TargetInvocationException

只需使用InnerException属性来获取 - 并可能抛出 - 原始异常。

例如:

try     
{
    method.Invoke(commandHandler, new[] { newCommand });
}
catch (TargetInvocationException e)
{     
    ExceptionService.SendException(e.InnerException);
}
相关问题