ASP.NET异常处理
除了以上的try-catch-finally的处理方式外,还有三种方式来捕获异常:
1. 页面级错误处理(通过Page_Error事件)
protected void Page_Error(object sender, EventArgs e) { string errorMsg = String.Empty; Exception currentError = Server.GetLastError(); errorMsg += "系统发生错误:<br/>"; errorMsg += "错误地址:" + Request.Url + "<br/>"; errorMsg += "错误信息:" + currentError.Message + "<br/>"; Response.Write(errorMsg); Server.ClearError();//清除异常(否则将引发全局的Application_Error事件) }
2. 应用程序级(global.asax)错误处理(通过Application_Error事件)
protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Exception iex = ex.InnerException; string errorMsg = String.Empty; string particular = String.Empty; if (iex != null) { errorMsg = iex.Message; particular = iex.StackTrace; } else { errorMsg = ex.Message; particular = ex.StackTrace; } //AddLog(errorMsg, particular); Server.ClearError();//处理完及时清理异常 }
3. 应用程序配置(web.config)
<system.web> <!--mode有三种值:On,Off,RemoteOnly,defaultRedirect出现错误重定向的URL--> <customErrors mode="On" defaultRedirect="ErrorPage.htm"> <!--statusCode错误状态码,redirect错误重定向的URL--> <error statusCode="403" redirect="NoAccess.htm"/> <error statusCode="404" redirect="FileNoFound.htm"/> </customErrors> </system.web>
来源:https://www.cnblogs.com/abnormal/archive/2012/07/04/2577008.html