自定义错误处理和日志

发布于 2024-11-03 13:31:55 字数 249 浏览 4 评论 0原文

如您所知,处理错误的基本方法是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵你手 2024-11-10 13:31:56

你可以捕获特定的异常类型

Try
{do something}
catch (SystemException ex) { }
catch (InvalidOperationException ex) { }
catch (Exception ex) { }

这是你的意思吗?

否则,您可以实现异常处理程序类

You can catch specific Exception types

Try
{do something}
catch (SystemException ex) { }
catch (InvalidOperationException ex) { }
catch (Exception ex) { }

Is this what you mean?

Otherwise you can implement an Exception Handler Class

谁与争疯 2024-11-10 13:31:55

我相信解决此类问题的最佳方法之一是使用面向方面的编程。

事实上,您想要的东西必须:

  • 处理异常。
  • 记录异常。

有一个称为 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:

  • Handle exceptions.
  • Log exceptions.

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":

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文