asp.net - 我应该在 global.asax 中捕获所有异常吗?

标签 asp.net logging exception global-asax

如果我只是在 Web 应用程序中记录异常详细信息,我真的需要为每一层添加异常处理逻辑吗?为什么不让它们全部通过堆栈跟踪冒泡到 global.asax 并将它们记录在那里?

最佳答案

我建议不要在应用程序的任何层中使用任何异常处理逻辑,除非:

  • 该异常不是致命的,这意味着您可以采取一些操作来恢复,或者
  • 应用程序应继续运行,并且异常应被“忽略”。举个例子:在在线零售商处结账时,您会收到通过电子邮件发送的收据。如果失败 - 但其他订单处理成功 - 用户不应该看到错误页面。在这里,我们希望即使出现异常,工作流程也能继续。大多数异常(exception)情况不属于此类。

当然,异常 - 无论它们是否致命,或者是否应该“忽略” - 都需要记录并通知开发人员。最好通过 Application.Error 事件的事件处理程序来处理。是的,这可以在 Global.asax 中完成,但我认为使用基于 HTTP 模块的方法更干净,或者 Health MonitoringELMAH .

我写了一篇关于这个主题的文章,我想推荐给您 - Exception Handling Advice for ASP.NET Web Applications 。以下是文章摘要:

My advice for handling exceptions in an ASP.NET application can be boiled down to the following guidelines:

(a) Create and use a meaningful custom error page.

(b) In general, do not catch exceptions. Let them bubble up to the ASP.NET runtime. Some cases where catching an exception makes sense include:

  • When there is a plausible way to recover from the exception by performing some alternative logic,

  • When a peripheral part of the application's workflow throws and exception and that exception should not derail the entire application, and

  • When you need to include additional information with the exception by throwing a new exception that has the original exception as its inner exception.

(c) Log all exceptions to some persistent store and use email (or some other medium) to notify developers when an exception occurs in production. Consider using ELMAH or ASP.NET's built-in Health Monitoring system to facilitate this process.

关于asp.net - 我应该在 global.asax 中捕获所有异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4307683/

相关文章:

linux - 异常处理程序的实际代码驻留在 Linux 中的什么位置?

c++ - 未处理的异常得到处理(visual studio 2019 这么聪明还是我遗漏了什么?)

java - 如何在 Java 中更轻松地搜索日志中的错误?

java - 性能 : Checked and unchecked exceptions in JAVA

c# - 对于在 ASP.Net WebAPI 应用程序中存储枚举的位置是否有任何约定?

c# - Nuget 包管理器错误

logging - 如何在记录器中抑制 MVC 信息消息?

linux - 如何让 Forever 每天写入不同的日志文件?

c# - Calendar Extender 日期选择并转换为正确的格式

c# - 基于 Web 浏览器/设备(例如 iPhone)的 ASP.NET MVC 路由