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

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

 1 using  System.Text;
 2 using  System.Web;
 3 using  System.Configuration;
 4 using  System.IO;
 5
 6 namespace  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/archive/2008/07/14/1242713.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值