gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:43:05 25 4
gpt4 key购买 nike

如果我只是在 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/

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