asp.net异常处理和错误页配置

 最近做一个项目,直接拷贝了前辈写的程序,结果报错了查了半天都没查出原因,也看不出哪里报错,最后发现有一个错误被try...catch了,所以我们做项目的时候一般不需要try...catch。

假设所有的异常都没有处理那我们可以在global.asax里面处理

  protected void Application_Error(object sender, EventArgs e)
        {

        }

 错误页配置

1、在webconfig里面配置如下:

 <customErrors mode="RemoteOnly" defaultRedirect="~/PageError.htm">
      <error statusCode="403" redirect="NoAccess.htm" />
      <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>

  </system.web>

如上代码: mode有3种模式,如果配置为off他将把所有的错误原封不动的暴漏给用户配置为on的时候遇到错误会自动跳到不同的错误页面,最后一个RemoteOnly本地暴漏错误                 远程屏蔽错误显示指定页面。

2、把整个项目的错误记录到日志中

  private static ILog logger = LogManager.GetLogger(typeof(Global));

   protected void Application_Error(object sender, EventArgs e)
        {
            string errorMsg = Context.Error.Message + Environment.NewLine + Context.Error.StackTrace + Environment.NewLine + "==========================================================" + Environment.NewLine;
            //1.把错误记录的日志中
          
            logger.Error("网站出现未处理异常", HttpContext.Current.Server.GetLastError());
  Response.Redirect("~/demo.html");//其中demo页面在根目录 }
原文地址:https://www.cnblogs.com/yabisi/p/6007463.html