如何编写捕获异常并删除堆栈跟踪的属性?
我希望为函数(或类)编写一个属性,该属性将捕获抛出的任何异常并将其 StackTrace 属性设置为 string.Empty。我该怎么做?
编辑:
如果我无法在普通 C# 中完成此操作,如何使用 PostSharp 在 C# 中完成此操作?
I wish to write an attribute for a function (or class) that will catch any exception thrown and set its StackTrace
property to string.Empty
. How can I do this?
EDIT:
If I cannot accomplish this in plain C#, how can I do this in C# with PostSharp?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上必须抛出一个新的异常。 @Ani 的示例将简单地重新抛出已使用相同堆栈跟踪抛出的异常(由于您如何到达该方面,它是相同的)。引发新的异常将“更改”堆栈跟踪,但不会删除它。如果你想删除它,你将需要抛出你自己的类来覆盖堆栈跟踪属性。将旧异常传递给新异常将使旧异常成为内部异常(如果您想要的话)
您可以使用或不使用 PostSharp 来完成此操作。 关键是您的自定义异常类。
给出以下代码,
输出为
You actually have to throw a NEW exception. @Ani's example will simply rethrow the exception already thrown with the same stack trace (it's the same because of how you got to the aspect). Throwing a new exception will "change" the stack trace but it won't erase it. If you want to erase it, you will need to throw your own class that overrides the stack trace property. passing in the old exception to the new exception will make the old exception the inner exception (if you want that)
You can accomplish this with and without PostSharp. The key is your custom exception class.
Given the following code
the output is
异常的原始堆栈跟踪存储在 Exception 类的一个字段中。如果您想在不创建自己的异常类型的情况下删除它,您可以通过反射将其删除,如下所示:
您的异常将不再包含堆栈跟踪。
编辑 当然,你也可以在没有 PostSharp 的情况下完成同样的事情,只需在
catch
块中完成即可。The original stack trace of the exception is stored in a field in the
Exception
class. If you want to remove it without creating your own exception type, you can remove it via reflection like this:Your exception will no longer contain the stack trace.
Edit Of course you can accomplish the same thing without PostSharp too, just do it in the
catch
block.