.Net的错误机制

    //优先级1
    protected void Page_Error(object sender, EventArgs e)
    {
        Exception objErr = Server.GetLastError().GetBaseException();
        using (System.IO.StreamWriter  sw=new System.IO.StreamWriter("d:/log.txt",true))
        {
            sw.WriteLine("Page_Error:" + objErr.Message);
        }
        //Server.ClearError(); //调用,则优先级靠后的异常捕获机制不会生效.

    }

    //优先级2 //调用,则优先级靠后的异常捕获机制不会生效.
    protected void Page_Load(object sender, EventArgs e)
    {
        //this.ErrorPage = "http://my.lotour.com/i/5451821"; //若前面没有Server.ClearError()且<customErrors mode="On",则生效
    }

    //优先级3    
    void Application_Error(object sender, EventArgs e)
    {
        // 在出现未处理的错误时运行的代码
        Exception objErr = Server.GetLastError().GetBaseException();
        //Response.Write("Application_Error:" + objErr.Message);
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter("d:/log.txt", true))
        {
            sw.WriteLine(DateTime.Now.ToString()+"Application_Error:" + objErr.Message);
        }
        //Server.ClearError();//调用,则优先级靠后的异常捕获机制不会生效.
    }

   <!--优先级4 mode="On"生效, defaultRedirect是异常错误的默认跳转的页面,明确的错误则跳转到对应的redirect-->
    <customErrors mode="On" defaultRedirect="http://my.lotour.com/i/5505381">
      <error statusCode="403" redirect="NoAccess.htm"/>
      <error statusCode="404" redirect="http://my.lotour.com/i/5360655"/>
    </customErrors>

原文地址:https://www.cnblogs.com/tyhj-zxp/p/4760682.html