ASP.Net 异常 - 在页面中捕获或在 Global.asax 中处理(Application_Error)
在这里寻找以最佳实践为中心的答案和解释。
如果 ASP.Net 应用程序的表示层捕获并处理从业务层抛出的异常,或者是否应该允许这些异常冒出,则可以在 Global.ascx 中统一记录和处理它们的 Application_Error 处理程序?
即..
protected void Application_Error(object sender, EventArgs e)
{
logExceptionDetails(Server.GetLastError());
HttpContext.Current.Server.Transfer("~/Error.aspx");;
}
谢谢
Looking for best practice focused answers here with explanations.
Should the presentation layer of an ASP.Net app catch and handle exceptions thrown from the business layer, or should these be allowed to bubble out, where they can all be logged and handled uniformly in the Global.ascx's Application_Error handler?
ie..
protected void Application_Error(object sender, EventArgs e)
{
logExceptionDetails(Server.GetLastError());
HttpContext.Current.Server.Transfer("~/Error.aspx");;
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我处理异常的方法是让它们发生并使用 Elmah 记录它们,并使用内置的在自定义错误页面机制中通知我的用户出了问题。
所有这些都可以用零代码完成(在 web.config 中配置)。
My approach to Exceptions is to let them happen and log them with Elmah, and use the built-in Custom Error Page mechanism to notify my user that something went wrong.
All of that can be done with zero code (configured in web.config).
好吧,如果您需要真正“处理”异常,那么您需要在代码中可能发生异常的地方使用 try-catch 块。
您选择的方法取决于您预计事件发生的频率。如果事件确实是异常的并且是错误(例如意外的文件结束),则使用异常处理会更好,因为在正常情况下执行的代码较少。如果事件经常发生,那么使用编程方法来检查错误会更好。
但是,如果您正在查看“未捕获”的日志记录异常,那么您应该使用 Global 的错误事件,就像您所展示的那样。这是最佳实践。事实上,如果您将其实现为 HttpModule,那么您的异常处理是非侵入性的,可以插入其他应用程序或通过简单地更改 web.config 文件来删除。
看看 4GuysFromRolla 上的这篇文章
https://web.archive.org/web/20211020134127/https://www.4guysfromrolla.com/articles/081209-1.aspx
Well, if you need to truely "handle" the exception, then you'll need try-catch blocks in your code where the exceptions might happen.
The method you choose depends on how often you expect the event to occur. If the event is truly exceptional and is an error (such as an unexpected end-of-file), using exception handling is better because less code is executed in the normal case. If the event happens routinely, using the programmatic method to check for errors is better.
However, if you're looking at logging exceptions that have been "uncaught", then you should use Global's Error event like you've shown.This is the best practice. In fact if you implement this as an HttpModule then your Exception handling is non-intrusive and can plugged into other applications or removed by simply altering the web.config file.
Take a look at this article on 4GuysFromRolla
https://web.archive.org/web/20211020134127/https://www.4guysfromrolla.com/articles/081209-1.aspx