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

允我心安 提交于 2019-12-09 06:49:40

问题


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");
}

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".

I want to catch the exception that has been raised (which is CustomException), and pass it to the ExceptionService mechanism.

What am I doing wrong?


回答1:


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.

Just use the InnerException property to obtain - and potentially throw - the original exception.

So for example:

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


来源:https://stackoverflow.com/questions/32741529/exception-has-been-thrown-by-the-target-of-an-invocation-methodbase-invoke-meth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!