C# 调用的目标(MethodBase.Invoke方法)引发了异常
我想捕获在使用invoke方法调用的方法中抛出的异常C# 调用的目标(MethodBase.Invoke方法)引发了异常,c#,exception,reflection,invoke,C#,Exception,Reflection,Invoke,我想捕获在使用invoke方法调用的方法中抛出的异常 public void TestMethod() { try { method.Invoke(commandHandler, new[] { newCommand }); } catch(Exception e) { ExceptionService.SendException(e); } } 方法。调用调用以下方法: public void Registe
public void TestMethod()
{
try
{
method.Invoke(commandHandler, new[] { newCommand });
}
catch(Exception e)
{
ExceptionService.SendException(e);
}
}
方法。调用调用以下方法:
public void Register(/*parameters*/)
{
if(test_condition())
throw new CustomException("Exception Message");
}
问题是,在TestMethod中捕获CustomException时,catch语句上的e变量的类型不是CustomException。它有以下消息:“异常已被调用的目标抛出”
我希望捕获已引发的异常(即CustomException),并将其传递给ExceptionService机制
我做错了什么?是的,您正在通过反射调用该方法。因此,根据,如果目标方法引发异常,将引发异常 只需使用该属性获取并可能抛出原始异常 例如:
try
{
method.Invoke(commandHandler, new[] { newCommand });
}
catch (TargetInvocationException e)
{
ExceptionService.SendException(e.InnerException);
}