我想捕捉在使用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");
}问题是,当我在TestMethod中捕获CustomException时,catch语句中的e变量不是CustomException类型。它有以下消息:“调用的目标抛出了异常”。
我希望捕获已引发的异常(即CustomException),并将其传递给ExceptionService机制。
我做错了什么?
发布于 2015-09-23 21:57:31
是的,您正在通过反射调用该方法。因此,根据the documentation,如果目标方法抛出异常,就会抛出TargetInvocationException。
只需使用InnerException属性来获取-并可能抛出-原始异常。
举个例子:
try
{
method.Invoke(commandHandler, new[] { newCommand });
}
catch (TargetInvocationException e)
{
ExceptionService.SendException(e.InnerException);
}https://stackoverflow.com/questions/32741529
复制相似问题