[英]Exception has been thrown by the target of an invocation (MethodBase.Invoke Method)
我想捕獲在使用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機制。
我究竟做錯了什么?
是的,你通過反射調用方法。 因此,根據文檔 ,如果目標方法拋出異常,將拋出TargetInvocationException
。
只需使用InnerException
屬性來獲取 - 並可能拋出 - 原始異常。
例如:
try
{
method.Invoke(commandHandler, new[] { newCommand });
}
catch (TargetInvocationException e)
{
ExceptionService.SendException(e.InnerException);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.