简体   繁体   English

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

[英]Exception has been thrown by the target of an invocation (MethodBase.Invoke Method)

I want to catch the exceptions that are thrown in methods called with invoke method. 我想捕获在使用invoke方法调用的方法中抛出的异常。

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

method.Invoke calls the following method: method.Invoke调用以下方法:

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

The problem is that when I catch the CustomException, in the TestMethod, the e variable on the catch statement has NOT the type CustomException. 问题是当我捕获CustomException时,在TestMethod中,catch语句中的e变量没有类型CustomException。 It has the following message: "Exception has been thrown by the target of an invocation". 它有以下消息:“调用目标已抛出异常”。

I want to catch the exception that has been raised (which is CustomException), and pass it to the ExceptionService mechanism. 我想捕获已引发的异常(这是CustomException),并将其传递给ExceptionService机制。

What am I doing wrong? 我究竟做错了什么?

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. 因此,根据文档 ,如果目标方法抛出异常,将抛出TargetInvocationException

Just use the InnerException property to obtain - and potentially throw - the original exception. 只需使用InnerException属性来获取 - 并可能抛出 - 原始异常。

So for example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM