gpt4 book ai didi

c# - 你能得到抛出异常的方法名吗?

转载 作者:行者123 更新时间:2023-11-30 13:15:01 24 4
gpt4 key购买 nike

是否有一个 C# 方法返回最上层的调用者,即抛出异常的我的方法 的名称,即使实际异常 是由另一个抛出的(例如,当我的方法调用它时数据库驱动程序错误)?

调用方 -> MyMethod -> DbDriver(错误)

我想要“MyMethod”,而不是“DbDriver”

我宁愿不在链上一直重新抛出异常。

我目前的问题是遍历 StackTrace 帧,并使用 MethodBase.GetCurrentMethod().DeclaringType 解析我的方法。

是否有内置方法来获取此信息或更优雅的解决方案?

谢谢!

最佳答案

使用Exception.TargetSite获取方法名的属性

Gets the method that throws the current exception.

关于c# - 你能得到抛出异常的方法名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16666338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com