文章出處

畢竟人不是神,誰寫的程序都會有bug,有了bug不可怕,可怕的是出錯了,你卻不知道錯誤在哪里。所以我們需要將應用程序中拋出的所有異常都記錄起來,不然出了錯,找問題就能要了你的命。下面我們主要討論的是如何捕捉全局的異常。基本上在winform或web中捕獲全局異常的思路都是一樣的,在全局的應用程序對象中添加異常捕獲的代碼,并寫入日志文件中。

一.在Winform程序中捕獲全局異常

在winfrom中我們需要了解Application對象中的兩個事件

Application.ThreadException 事件--UI線程中某個異常未被捕獲時出現。

AppDomain.UnhandledException 事件--非UI線程中某個異常未被捕獲時出現。

我們需要在Program.cs中設置異常的捕捉代碼(如下圖所示)。LogHelper類是自定義的日志幫助類,在前面的幾篇文章中已經有涉及到。

image

需要在Program.cs中添加的代碼如下所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Text;
using Common;

namespace testLog4N
{
    static class Program
    {
        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            BindExceptionHandler();//綁定程序中的異常處理
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        /// <summary>
        /// 綁定程序中的異常處理
        /// </summary>
        private static void BindExceptionHandler()
        {
            //設置應用程序處理異常方式:ThreadException處理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //處理UI線程異常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            //處理未捕獲的異常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        /// <summary>
        /// 處理UI線程異常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LogHelper.ErrorLog(null, e.Exception as Exception);
        }
        /// <summary>
        /// 處理未捕獲的異常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogHelper.ErrorLog(null, e.ExceptionObject as Exception);
        }
    }
}

示例性代碼下載

二、在Web中捕獲全局異常

我們只需要在Global.asax文件中添加異常捕獲的代碼即可。

image

完整Global.asax代碼如下所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Common;

namespace WebApplication_testLog4Net
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // 在應用程序啟動時運行的代碼

        }

        void Application_End(object sender, EventArgs e)
        {
            //  在應用程序關閉時運行的代碼

        }

        void Application_Error(object sender, EventArgs e)
        {
            // 在出現未處理的錯誤時運行的代碼
            Exception objExp = HttpContext.Current.Server.GetLastError();
            LogHelper.ErrorLog("<br/><strong>客戶機IP</strong>:" + Request.UserHostAddress + "<br /><strong>錯誤地址</strong>:" + Request.Url , objExp);
        }

        void Session_Start(object sender, EventArgs e)
        {
            // 在新會話啟動時運行的代碼
           }

        void Session_End(object sender, EventArgs e)
        {
            // 在會話結束時運行的代碼。 
            // 注意: 只有在 Web.config 文件中的 sessionstate 模式設置為
            // InProc 時,才會引發 Session_End 事件。如果會話模式設置為 StateServer 
            // 或 SQLServer,則不會引發該事件。

        }

    }
}

示例程序下載

三、在WPF中捕獲全局異常

我們只需要在App.xaml文件中添加異常捕獲的代碼即可。

image

在WPF中捕獲全局異常主要涉及到以下兩個事件

1、AppDomain.UnhandledException 事件--當某個異常未被捕獲時出現。主要指的是非UI線程。

2、Application.DispatcherUnhandledException 事件--如果異常是由應用程序引發,但未處理,發生。主要指的是UI線程。

完整的App.xaml文件如下所示

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using Common;

namespace WpfApplication1
{
    /// <summary>
    /// App.xaml 的交互邏輯
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is System.Exception)
            {
                LogHelper.ErrorLog(null, (System.Exception)e.ExceptionObject);
            }
        }

        public static void HandleException(Exception ex)
        {
            LogHelper.ErrorLog(null,ex);
        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            LogHelper.ErrorLog(null, e.Exception);
        }
    
    }
}

示例代碼下載


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()