1. 程式人生 > >錯誤處理機制跳轉錯誤頁面

錯誤處理機制跳轉錯誤頁面

錯誤處理機制 程式碼 

 protected void Application_Error(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            Exception exception = ctx.Server.GetLastError();
           // Exception exception_s = Server.GetLastError();
            //HttpException ex = exception_s as HttpException;
            string directUrl = "Error.aspx?error=";
            if (exception != null)
            {
                string m = exception.Message;

                string errorInfo = "URL:<strong>" + ctx.Request.RawUrl.ToString() + "<strong><br/>Source:<strong>" + exception.Source
                + "<strong><br/>Message:<strong>" + exception.Message + "<>";
                if (!m.Contains("不存在"))
                {
                    errorInfo += "<br/>錯誤資訊為:<strong>" + exception.InnerException.Message + "<>";
                }
                if (exception is HttpException)
                {
                    HttpException ex = exception as HttpException;
                    int httpCode = ex.GetHttpCode();
                    errorInfo += "<br />Code:<strong>" + httpCode.ToString() + "<>";
                }
                string url = ctx.Request.Url.ToString();
                string suburl = url.Substring(0, url.ToString().IndexOf("/Admin/") + 1);
                directUrl = suburl + directUrl + errorInfo;
                //directUrl += "&referurl=" + ctx.Request.Url.ToString();
                //if (httpCode == 404)
                //{
                //    directUrl = "~/DefaultError.html?error=" + errorInfo;
                //}
                //if (httpCode == 403 || httpCode == 402 || httpCode == 401)
                //{
                //    directUrl = "~/DefaultError.html?error=" + errorInfo;
                //}
                //}
                ctx.Items.Add("LastError", errorInfo);
                ctx.Server.ClearError();
            }
            try
            {
                ctx.Response.Redirect(directUrl);
            }
            catch
            { }
            //ctx.Server.Transfer(directUrl);
        }
錯誤處理機制 程式碼, 要的趕緊貼上到記事本
就寫一個方法,頁面所有報錯 都指向一個頁面就OK了

這個方法 必須寫在 Global.asax 檔案中,放在根目錄