自定义错误处理和日志
如您所知,处理错误的基本方法是 try...catch...finally 结构。
如果我们想处理每个错误并将其保存到文件中,则必须在 catch 部分添加一行以保存错误详细信息。
问题是: 对于覆盖捕获事件有什么解决方案吗?
换句话说,考虑与其他应用程序事件类似的 try ... catch ... finally 结构并覆盖 catch 部分,运行我们的自定义代码,然后运行 catch 部分代码。
是否可以?
As you know the basic method for handle error is try ... catch ... finally structure.
If we want to handle every error and save it into a file, we have to add one line to catch section for save error details.
The question is:
Is there any solution for override catch event?
In other words, consider try ... catch ... finally structure similar to other application events and override catch section, run our custom code next run catch section code.
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以捕获特定的异常类型
这是你的意思吗?
否则,您可以实现异常处理程序类
You can catch specific Exception types
Is this what you mean?
Otherwise you can implement an Exception Handler Class
我相信解决此类问题的最佳方法之一是使用面向方面的编程。
事实上,您想要的东西必须:
有一个称为 IL 编织的概念,它基于编译后代码注入,可以简化面向方面的编程。
也就是说,您可以在执行方法和属性之前和之后执行一些操作,归根结底,这就是“处理任何程序集成员中引发的任何异常”,不是吗?
例如,我对 PostSharp 有一些经验,它实现了 IL 编织,并且使用起来非常容易:它是基于属性的。
您需要实现一个派生一些 PostSharp 基本属性的自定义属性,并且它可以覆盖在执行您放置属性的方法/属性之前和之后调用的某些方法。
异常处理可以实现为“HandleExceptionAttribute”并记录“LogAttribute”(这只是一个示例!)。
了解有关 PostSharp 的更多信息(如果我没记错的话,它有一个免费的社区版本):
还有一些“操作方法”:
I believe one of best ways of implementing these kind of problems is by using aspect-oriented programming.
In fact, you want something that must:
There's a concept called IL weaving that's based on post-compilation code injection which eases aspect-oriented programming.
That's you can do something before and after executing methods and properties and, at the end of the day, this is "handling any exception thrown in any assembly member", isn't it?
For example, I've some experience with PostSharp, which implements IL weaving and makes it incredibly easy to work with it: it's attribute-based.
You need to implement a custom attribute deriving some PostSharp base one, and it can override some method that will be invoked before and other after executing the method/property where you place your atrribute.
Exception handling could be implemented as a "HandleExceptionAttribute" and logging "LogAttribute" (it's just an example!).
Learn more about PostSharp on (if I'm not wrong, it has a free community edition):
And some "how-to":