我想捕获在用invoke方法调用的方法中引发的异常。
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"); }问题是当我在CustomMethod中捕获CustomException时,e catch语句上的变量的类型不是CustomException。它具有以下消息:调用的目标已引发异常。
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".
我想捕获已引发的异常(这是CustomException),并将其传递给ExceptionService机制。
I want to catch the exception that has been raised (which is CustomException), and pass it to the ExceptionService mechanism.
我在做什么错了?
推荐答案是的,你是通过反射重新调用该方法。因此,根据文档, TargetInvocationException 。
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.
只需使用 InnerException 属性
Just use the InnerException property to obtain - and potentially throw - the original exception.
因此,例如:
try { method.Invoke(commandHandler, new[] { newCommand }); } catch (TargetInvocationException e) { ExceptionService.SendException(e.InnerException); }更多推荐
调用的目标(MethodBase.Invoke方法)已引发异常
发布评论