调用的目标(MethodBase.Invoke方法)已引发异常

编程入门 行业动态 更新时间:2024-10-26 00:29:25
本文介绍了调用的目标(MethodBase.Invoke方法)已引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想捕获在用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方法)已引发异常

本文发布于:2023-11-04 17:37:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1558580.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   目标   方法   Invoke   MethodBase

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!