捕获ASP.NET程序发生的异常

捕获ASP.NET异常,这种文章在网上已经屡见不鲜了,在这之前,我也看了不少别人写的代码,学了别人不少东西。在别人的基础上,我添加了一些自己写的东西,现在贴出来,共享一下,希望能对大家有点帮助。

 1using System.Text;
 2using System.Web;
 3using System.Configuration;
 4using System.IO;
 5
 6namespace HNRInfo.Framework.HttpModule
 7{
 8    /// <summary>
 9    /// 捕获未处理的系统的错误,将错误添加的数据库中,同时指向一个友好的错误页面
10    /// </summary>

11    public class CatchError : IHttpModule
12    {
13        private static string sysErrorPage = ConfigurationManager.AppSettings["SysErrorPage"].ToString();
14
15        public void Dispose()
16        {
17        }

18
19        public void Init(HttpApplication context)
20        {
21            context.Error += new EventHandler(SaveError);
22        }

23        //将捕获的错误信息插入数据库
24        private void SaveError(object sender, EventArgs e)
25        {
26            HttpContext context = ((HttpApplication)sender).Context;
27            string path = context.Request.RawUrl;
28            string hostIP = context.Request.UserHostAddress;
29
30            string title = string.Empty;
31            string info = string.Empty;
32
33            GetLastError(context.Server.GetLastError(), ref title, ref info);
34
35            HNRInfo.Model.SystemError errorModel = new HNRInfo.Model.SystemError();
36            errorModel.errorTitle = title;
37            errorModel.errorInfo = info;
38            errorModel.occurUrl = path;
39            errorModel.hostIP = hostIP;
40
41            HNRInfo.DALFactory.PlatFactory.SystemError.Add(errorModel);
42
43            //重定向到友好的错误页面
44            context.Server.Transfer(sysErrorPage, false);
45        }

46
47        /// <summary>
48        /// 找到导致异常的最初错误
49        /// </summary>

50        private void GetLastError(Exception e, ref string title, ref string info)
51        {
52            if (e.InnerException != null)
53                GetLastError(e.InnerException, ref title, ref info);
54            else
55            {
56                title = e.Message;
57                info = e.StackTrace;
58            }

59        }

60    }

61}

62

35-41行,是存入数据库的一些操作,这几行代码,不用理会。由于这段代码的在一个名为HNRInfo.Framework的程序集中,故web.config中的配置为:
      <httpModules>
        
<!--捕获错误-->
        
<add type="HNRInfo.Framework.HttpModule.CatchError, HNRInfo.Framework" name="HNRInfo.Framework" />
      
</httpModules>

代码没有什么,挺简单的,简单是因为.NET在后台已经为我们做了很多复杂的工作。我觉得大家如果有时间的话,可以看看这个StackTrace类型的用法,下边列出一些朋友的文章(关于StackTrace的用法):
浅析StackTrace
使用 StackTrace 获得更多跟 Exception 有关的信息
用System.Diagnostices.StackTrace取得呼叫堆疊資訊。
原文地址:https://www.cnblogs.com/fengfeng/p/1242713.html