ASP.NET异常处理

天涯浪子 提交于 2020-01-27 22:12:16

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>
复制代码

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!