asp.net捕獲全局未處理異常的幾種方法


1.通過HttpModule來捕獲未處理的異常【推薦】

首先需要定義一個HttpModule,並監聽未處理異常,代碼如下:

        public void Init(HttpApplication context)
        {
            context.Error += new EventHandler(context_Error);
        }

        public void context_Error(object sender, EventArgs e)
        {
            //此處處理異常
            HttpContext ctx = HttpContext.Current;
            HttpResponse response = ctx.Response;
            HttpRequest request = ctx.Request;

            //獲取到HttpUnhandledException異常,這個異常包含一個實際出現的異常
            Exception ex = ctx.Server.GetLastError();
            //實際發生的異常
            Exception iex = ex.InnerException;

            response.Write("來自ErrorModule的錯誤處理<br />");
            response.Write(iex.Message);

            ctx.Server.ClearError();
        }

 

然后在web.config中加入配置信息:

        <httpModules>
            <add name="errorCatchModule" type="WebModules.ErrorHandlerModule, WebModules" />
        </httpModules>

 

這樣就可以處理來自webApp中未處理的異常信息了。

之所以推薦這種方法,是因為這種實現易於擴展、通用;這種方法也是用的最多的。

 

 

2.Global中捕獲未處理的異常

在Global.asax中有一個Application_Error的方法,這個方法是在應用程序發生未處理異常時調用的,我們可以在這里添加處理代碼:

        void Application_Error(object sender, EventArgs e)
        {
            //獲取到HttpUnhandledException異常,這個異常包含一個實際出現的異常
            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;
            }
            HttpContext.Current.Response.Write("來自Global的錯誤處理<br />");
            HttpContext.Current.Response.Write(errorMsg);

            Server.ClearError();//處理完及時清理異常
        }

 

這種處理方式同樣能夠獲取全局未處理異常,但相對於使用HttpModule的實現,顯得不夠靈活和通用。

HttpModule優先於Global中的Application_Error方法。

 

3.頁面級別的異常捕獲

我們還可以在頁面中添加異常處理方法:在頁面代碼中添加方法Page_Error,這個方法會處理頁面上發生的未處理異常信息。

        protected void Page_Error(object sender, EventArgs e)
        {
            string errorMsg = String.Empty;
            Exception currentError = Server.GetLastError();
            errorMsg += "來自頁面的異常處理<br />";
            errorMsg += "系統發生錯誤:<br />";
            errorMsg += "錯誤地址:" + Request.Url + "<br />";
            errorMsg += "錯誤信息:" + currentError.Message + "<br />";
            Response.Write(errorMsg);
            Server.ClearError();//清除異常(否則將引發全局的Application_Error事件)
        }

 這種方法會優先於HttpModule和Global。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM