構建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的後臺管理系統(13)-系統日誌和異常的處理③

系列目錄javascript

上一節咱們講了如何捕獲異常和記錄日誌,這一節咱們講,沒有捕獲的或者忘記捕獲的異常包括404錯誤等,咱們統一處理這個異常。html

這一講是利用 Application_Error 捕獲全部異常,全局的異常處理爲了減小代碼,統一異常處理,Application_Error位於Global.asax裏面,java

protected void Application_Error(object sender, EventArgs e)數據庫

當一個異常在調用堆棧中沒有被處理,也沒有被框架代碼處理時,咱們說這個異常未處理,它將被ASP.NET捕獲框架

它將捕獲全部 Application 級別的 UnhandleException 和 HttpException(好比:訪問的頁面不存在等)ide

總之,在這裏處理的話,那麼在頁面中的全部 try/catch 處理均可以不要了,可是咱們爲了記錄日誌,在BLL層仍是要try catch網站

對此未處理錯誤的處理方法是顯示一個頁面,列出該未處理異常的詳細狀況。ui

咱們經過 Application_Error事件把錯誤寫進對應的文件裏面或者數據庫中。this

 /// <summary>
        /// 全局的異常處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            string s = HttpContext.Current.Request.Url.ToString();
            HttpServerUtility server = HttpContext.Current.Server;
            if (server.GetLastError() != null)
            {
                Exception lastError = server.GetLastError();
                // 此處進行異常記錄,能夠記錄到數據庫或文本,也可使用其餘日誌記錄組件。
                ExceptionHander.WriteException(lastError);
                Application["LastError"] = lastError;
                int statusCode = HttpContext.Current.Response.StatusCode;
                string exceptionOperator = "/SysException/Error";
                try
                {
                    if (!String.IsNullOrEmpty(exceptionOperator))
                    {
                        exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
                        string url = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
                        string script = String.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
                        Response.Write(script);
                        Response.End();
                    }
                }
                catch { }
            }
        }

嘿嘿,我創造了一個錯誤 Convert.ToInt16("dddd");下面是錯誤的顯示頁面url

 

關於錯誤頁面的製做在控制器SysExceptionController增長

       public ActionResult Error()
        {

            BaseException ex = new BaseException();
            return View(ex);
        }

添加BaseException類

 public class BaseException
    {
        #region 變量
        private string exceptionMessage;
        private string exceptionName;
        private string innerExceptionMessage;
        private string innerExceptionName;
        private bool isShow;
        private Exception outermostException;
        private string sourceErrorFile;
        private string sourceErrorRowID;
        private string stackInfo;
        private string targetSite;
        #endregion

        #region 屬性
        public string ErrorPageUrl
        {
            get
            {
                return this.GetExceptionUrl();
            }
        }
        public Exception Exception
        {
            get
            {
                return (HttpContext.Current.Session["Exception"] as Exception);
            }
            private set
            {
                HttpContext.Current.Session["Exception"] = value;
            }
        }
        public string ExceptionMessage
        {
            get
            {
                return this.exceptionMessage;
            }
            private set
            {
                this.exceptionMessage = value;
            }
        }
        public string ExceptionName
        {
            get
            {
                return this.exceptionName;
            }
            private set
            {
                this.exceptionName = value;
            }
        }
        public string InnerExceptionMessage
        {
            get
            {
                return this.innerExceptionMessage;
            }
            private set
            {
                this.innerExceptionMessage = value;
            }
        }
        public string InnerExceptionName
        {
            get
            {
                return this.innerExceptionName;
            }
            private set
            {
                this.innerExceptionName = value;
            }
        }
        public bool IsShowStackInfo
        {
            get
            {
                return this.isShow;
            }
            private set
            {
                this.isShow = value;
            }
        }
        public string SourceErrorFile
        {
            get
            {
                return this.sourceErrorFile;
            }
            private set
            {
                this.sourceErrorFile = value;
            }
        }
        public string SourceErrorRowID
        {
            get
            {
                return this.sourceErrorRowID;
            }
            private set
            {
                this.sourceErrorRowID = value;
            }
        }
        public string StackInfo
        {
            get
            {
                return this.stackInfo;
            }
            private set
            {
                this.stackInfo = value;
            }
        }
        public string TargetSite
        {
            get
            {
                return this.targetSite;
            }
            private set
            {
                this.targetSite = value;
            }
        }
        #endregion


        public BaseException()
        {
            this.outermostException = null;
            this.exceptionName = null;
            this.exceptionMessage = null;
            this.innerExceptionName = null;
            this.innerExceptionMessage = null;
            this.targetSite = null;
            this.stackInfo = null;
            this.sourceErrorFile = null;
            this.sourceErrorRowID = null;
            this.isShow = false;
            try
            {
                this.Exception = HttpContext.Current.Application["LastError"] as Exception;
                if (this.Exception != null)
                {
                    this.outermostException = this.Exception;
                    if ((this.Exception is HttpUnhandledException) && (this.Exception.InnerException != null))
                    {
                        this.Exception = this.Exception.InnerException;
                    }
                    this.ExceptionName = this.GetExceptionName(this.Exception);
                    this.ExceptionMessage = this.GetExceptionMessage(this.Exception);
                    if (this.Exception.InnerException != null)
                    {
                        this.InnerExceptionName = this.GetExceptionName(this.Exception.InnerException);
                        this.InnerExceptionMessage = this.GetExceptionMessage(this.Exception.InnerException);
                    }
                    this.TargetSite = this.GetTargetSite(this.Exception);
                    this.StackInfo = this.GetStackInfo(this.Exception);
                    if ((this.outermostException is HttpUnhandledException) && (this.outermostException.InnerException != null))
                    {
                        this.StackInfo = this.StackInfo + "\r\n<a href='#' onclick=\"if(document.getElementById('phidden').style.display=='none') document.getElementById('phidden').style.display='block'; else document.getElementById('phidden').style.display='none'; return false;\"><b>[" + this.outermostException.GetType().ToString() + "]</b></a>\r\n";
                        this.StackInfo = this.StackInfo + "<pre id='phidden' style='display:none;'>" + this.outermostException.StackTrace + "</pre>";
                    }
                    this.SourceErrorFile = this.GetSourceErrorFile();
                    this.SourceErrorRowID = this.GetSourceErrorRowID();
                    this.IsShowStackInfo = true;
                }
                HttpContext.Current.Session["LastError"] = null;
            }
            catch (Exception exception)
            {
                this.ExceptionMessage = "異常基頁出錯" + exception.Message;
            }
        }

        #region 方法
        private string GetExceptionMessage(Exception ex)
        {
            return ex.Message;
        }

        private string GetExceptionMessageForLog()
        {
            StringBuilder builder = new StringBuilder(50);
            builder.AppendFormat("<ExceptionName>{0}</ExceptionName>", this.ExceptionName);
            builder.AppendFormat("<ExceptionMessage>{0}</ExceptionMessage>", this.ExceptionMessage);
            builder.AppendFormat("<InnerExceptionName>{0}</InnerExceptionName>", this.InnerExceptionName);
            builder.AppendFormat("<InnerExceptionMessage>{0}</InnerExceptionMessage>", this.InnerExceptionMessage);
            builder.AppendFormat("<TargetSite>{0}</TargetSite>", this.TargetSite);
            builder.AppendFormat("<ErrorPageUrl>{0}</ErrorPageUrl>", this.ErrorPageUrl);
            builder.AppendFormat("<SourceErrorFile>{0}</SourceErrorFile>", this.SourceErrorFile);
            builder.AppendFormat("<SourceErrorRowID>{0}</SourceErrorRowID>", this.SourceErrorRowID);
            return builder.ToString();
        }

        private string GetExceptionMessageForMail()
        {
            StringBuilder builder = new StringBuilder(50);
            builder.Append("<ExceptionInfo>");
            builder.Append(this.GetExceptionMessageForLog());
            builder.AppendFormat("<StackInfo><![CDATA[{0}]]></StackInfo>", this.StackInfo);
            builder.Append("</ExceptionInfo>");
            return builder.ToString();
        }

        private string GetExceptionName(Exception ex)
        {
            string str = null;
            if (ex != null)
            {
                str = ex.GetType().FullName;
            }

            return str;
        }

        private string GetExceptionUrl()
        {
            string str = null;
            if (HttpContext.Current.Request["ErrorUrl"] != null)
            {
                str = HttpContext.Current.Request["ErrorUrl"].ToString();
            }
            return str;
        }

        private string GetSourceErrorFile()
        {
            string stackInfo = this.StackInfo;
            string[] strArray = new string[0];
            if (stackInfo == null)
            {
                return stackInfo;
            }
            strArray = stackInfo.Split(new string[] { "位置", "行號" }, StringSplitOptions.RemoveEmptyEntries);
            if (strArray.Length >= 3)
            {
                stackInfo = strArray[1];
                if (stackInfo.LastIndexOf(":") == (stackInfo.Length - 1))
                {
                    stackInfo = stackInfo.Substring(0, stackInfo.Length - 1);
                }
                return stackInfo;
            }
            return "";
        }
        private string GetSourceErrorRowID()
        {
            string stackInfo = this.StackInfo;
            string[] strArray = new string[0];
            if (stackInfo == null)
            {
                return stackInfo;
            }
            strArray = stackInfo.Split(new string[] { "行號" }, StringSplitOptions.RemoveEmptyEntries);
            if (strArray.Length >= 2)
            {
                stackInfo = strArray[1].Trim();
                string[] strArray2 = stackInfo.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                if (strArray2.Length >= 2)
                {
                    stackInfo = strArray2[0];
                }
                return stackInfo;
            }
            return "";
        }
        private string GetStackInfo(Exception ex)
        {
            string str = null;
            if (ex != null)
            {
                str = "<b>[" + ex.GetType().ToString() + "]</b>\r\n" + ex.StackTrace;
                if (ex.InnerException != null)
                {
                    str = this.GetStackInfo(ex.InnerException) + "\r\n" + str;
                }
            }
            return str;
        }
        private string GetTargetSite(Exception ex)
        {
            string str = null;
            if (ex != null)
            {
                ex = this.GetBenmostException(ex);
                MethodBase targetSite = ex.TargetSite;
                if (targetSite != null)
                {
                    str = string.Format("{0}.{1}", targetSite.DeclaringType, targetSite.Name);
                }
            }
            return str;
        }
        protected Exception GetBenmostException(Exception ex)
        {
            while (true)
            {
                if (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                else
                {
                    return ex;
                }
            }
        }
        #endregion
    }
BaseException

添加Error視圖

@model App.Admin.Controllers.BaseException

@{
    ViewBag.Title = "異常處理頁面";
    Layout = "~/Views/Shared/_Index_Layout.cshtml";
}

<h2>系統錯誤</h2>
<div style="text-align:center;">
        <table width="100%" class="blueTab" border="0" cellspacing="1" cellpadding="1">
            <tr>
                <td colspan="3">
                    <table cellspacing="0" cellpadding="0" width="100%" border="0">
                        <tbody>
                            <tr>
                                <td >
                                    &nbsp;錯誤處理頁面</td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
            <tr id="youhaotishi" >
                <td colspan="2" align="left">
                    &nbsp;歡迎您光臨本網站!網站運行發生錯誤,請與管理員聯繫。錯誤緣由可能以下:
                    <br />
                    &nbsp;&nbsp;&nbsp;1.非法訪問頁面.
                    <br />
                    &nbsp;&nbsp;&nbsp;2.您輸入的數據錯誤.
                    <br />
                    &nbsp;&nbsp;&nbsp;3.您訪問的頁面不存在.
                    <br />
                    &nbsp;&nbsp;&nbsp;4.內容不存在,或已被刪除.
                    <br />
                    &nbsp;&nbsp;&nbsp;5.系統忙,請稍候再試.
                </td>
            </tr>
            <tbody id="detailInformation" style="display: none;">
                    <tr>
                <td width="20%" class="alignRight" nowrap>
                    <strong>出錯頁面:</strong>
                </td>
                <td  class="alignLeft">
                    @Html.DisplayFor(model => model.ErrorPageUrl) </td>
                </tr>
                <tr>
                    <td class="alignRight" nowrap>
                        <strong>異常名稱:</strong>
                    </td>
                    <td class="alignLeft">
                        @Html.DisplayFor(model => model.ExceptionName) </td>
                </tr>
                <tr>
                    <td class="alignRight" nowrap>
                        <strong>異常信息:</strong>
                    </td>
                    <td class="alignLeft">
                        @Html.DisplayFor(model => model.ExceptionMessage) </td>
                </tr>
                <tr id="trInnerExceptionName" runat="server">
                    <td class="alignRight" nowrap>
                        <strong>內部異常名稱:</strong>
                    </td>
                    <td class="alignLeft">
                        @Html.DisplayFor(model => model.InnerExceptionName) </td>
                </tr>
                <tr id="trInnerExceptionMessage" runat="server">
                    <td class="alignRight" nowrap>
                        <strong>內部異常信息:</strong>
                    </td>
                    <td class="alignLeft">
                        @Html.DisplayFor(model => model.InnerExceptionMessage) 
                        </td>
                </tr>
                <tr id="trExceptionMethod" runat="server">
                    <td class="alignRight" nowrap>
                        <strong>方法名稱:</strong>
                    </td>
                    <td class="alignLeft" style="background-color: #ffffcc;">
                        &nbsp;@Html.DisplayFor(model => model.TargetSite) </td>
                </tr>
                <tr id="trExceptionSource" runat="server">
                    <td class="alignRight" nowrap>
                        <strong>源文件:</strong>
                    </td>
                    <td class="alignLeft" style="background-color: #ffffcc;">
                        @Html.DisplayFor(model => model.SourceErrorFile) 
                    </td>
                </tr>
                <tr id="trExceptionRowId" runat="server">
                    <td class="alignRight" nowrap>
                        <strong>行號:</strong>
                    </td>
                    <td class="alignLeft" style="background-color: #ffffcc; color: Red">
                        &nbsp;@Html.DisplayFor(model => model.SourceErrorRowID) </td>
                </tr>
                <tr runat="server" id="trStack" visible="false">
                    <td class="alignRight">
                        <strong>堆棧跟蹤:</strong>
                    </td>
                    <td class="alignLeft" style="background-color: #ffffcc;">
                        <code>
                            <pre id="litStack"><textarea name="errormsg" cols="80" rows="30" readonly="readonly">@Html.DisplayFor(model => model.StackInfo) </textarea> </pre>
                        </code>
                    </td>
                </tr>
            </tbody>            
        </table>
        <a id="showMessage" href="#" onclick="ShowErrorMessage();return false;">顯示詳細信息</a>
    </div>

<script type="text/javascript">

    var isShowMessage = true;

    function ShowErrorMessage() {

        var obj = document.getElementById("showMessage")
        var detailInformation = document.getElementById("detailInformation");
        var youhaotishi = document.getElementById("youhaotishi");

        if (isShowMessage) {
            obj.innerText = "隱藏詳細信息";
            isShowMessage = false;
            detailInformation.style.display = "block";
            youhaotishi.style.display = "none";
        }
        else {
            obj.innerText = "顯示詳細信息";
            isShowMessage = true;
            detailInformation.style.display = "none";
            youhaotishi.style.display = "block";
        }

    }
</script>
Error.cshtml

 因爲系統是後臺系統,我並無作得很漂亮的錯誤頁面(實際很醜),你們發貨你的想象力和美工能力,造一個好看的,記得共享給我,有獎

相關文章
相關標籤/搜索