ASP.NET 中对于异常的处理

在ASP.NET编程中,如何对未捕获的异常进行统一的处理(或者称为响应),有两种方式

1. 通过Global.asax文件中编写Application_Error事件

private static string LOG_SOURCE = ConfigurationManager.AppSettings["Event Log Source"];

// If an exception is thrown in the application then log it to an event log
protected void Application_Error(object sender, EventArgs e) {
    Exception x = Server.GetLastError().GetBaseException();
    EventLog.WriteEntry(LOG_SOURCE, x.ToString(), EventLogEntryType.Error);
}   

这个事件能捕获所有未处理的异常。一般在这里进行日志的记录(如果需要的话)

 

2.通过配置customError元素

<customErrors defaultRedirect="Error.aspx" mode="RemoteOnly"/>

这里的mode有三个可能性:On,Off,RemoteOnly。设置为On表示不管是在本地还是在远程访问都显示详细的错误消息,而不是Redirect到我们的页面去。Off则反之。而RemoteOnly则表示只有在远程的情况下才使用自定义错误页面

这样就可以,发生错误的时候,把用户导航到一个统一的页面。我们一般不需要(也最好不要)把错误的详细信息告诉用户。

image 

image

需要注意一下,如果程序是在debug模式,那么以上都会失效。

<compilation debug="true">

所以,我们规定正式发布的程序都需要把调试模式关闭,这另外一方面还可以提高性能。

原文地址:https://www.cnblogs.com/chenxizhang/p/1331777.html