·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> global中捕获异常

global中捕获异常

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

  前言:由于现在日志非常重要,但是在哪里打写日志比较好呢,我选择的是在global中,把错误代码网上抛,而不是在底层写大量的try catch然后在catch中来写日志,每个catch中的写日志这样就会避免了很多重复代码。当然这是目前我们采取的一个方法,大家可以提出更好地方法来管理日志,下面我开始写代码

第一步:尽量抛弃项目中try catch。看下代码

PRivate void ExceptionTestOne()
        {           
                int a = 1;
                int b = 0;
                int c = a/b;                
        }

上面代码会抛一个异常

第二步:如果项目中必须用try catch怎么办,因为有时候连接wcf的时候如果出现异常时候我们需要关闭连接避免堵塞,那么我们就采取抛异常的方法

private void ExceptionTestTwo()
        {
            try
            {
                List<Simple> simples = null;
                simples.Add(new Simple() { Name = "发生异常" });
            }
            catch (Exception ex)
            {                
                throw new Exception("",ex);
            }        
        }

第三步:我们新建一个global.asax 在application_Error中把异常信息加入队列中 如下

 //创建一个静态的队列记录把异常都放在队列中
 private static Queue<Exception> queue = new Queue<Exception>();

 protected void Application_Error(object sender, EventArgs e)
         {
            Exception exp = Server.GetLastError();
            if (exp != null) {
                queue.Enqueue(exp);
            }

            Server.ClearError();
        }

第四步:异常信息加入日志(这里为了简单就写入txt文本中了)

protected void Application_Start(object sender, EventArgs e) {
            ThreadPool.QueueUserWorkItem(a => {
                while (true) {
                    try {
                        if (queue.Count > 0) {
                            Exception ex = queue.Dequeue();
                            WriteLog(ex);
                        }
                        else {
                            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
                        }
                    }
                    catch (Exception ex) {
                    WriteLog(ex);

} } }); }
    private void WriteLog(Exception ex)
        {
            if (!File.Exists(@"E:\C#系列\ExceptionDealWith\ExceptionDealWith\Log.txt")) {
                FileStream fs1 = new FileStream(@"E:\C#系列\ExceptionDealWith\ExceptionDealWith\Log.txt", FileMode.Create, Fileaccess.Write);//创建写入文件 
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(ex.Message);//开始写入值
                sw.Close();
                fs1.Close();
            }
            else
            {
                StreamWriter sr = File.AppendText(@"E:\C#系列\ExceptionDealWith\ExceptionDealWith\Log.txt");    
                sr.WriteLine(ex.Message);
                sr.Close();                
            }
        }

当然接入错误信息你可以多定义几个比喻ip地址,堆栈信息错误等基本就是这么多了。这是基本思路。有日志了我就就可以根据时间,ip等进行查询日志日志信息

 下载