Application_Error的使用

 Application_Error位于Global.asax里面,protected void Application_Error(object sender, EventArgs e)。当一个异常在调用堆栈中没有被处理,也没有被框架代码处理时,我们说这个异常未处理,它将被ASP.NET捕获,ASP.NET对此未处理错误的处理方法是显示一个页面,列出该未处理异常的详细情况。我们可通过 Application_Error事件把错误写进对应的文件里面。

复制代码
        protected void Application_Error(object sender, EventArgs e)
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Request.PhysicalApplicationPath + "\\errlog.txt", true, System.Text.Encoding.UTF8);

            Exception objErr = Server.GetLastError().GetBaseException();
            string error = "发生异常页: " + Request.Url.ToString() + "\n";
            error += "异常信息: " + objErr.Message + "\n";
            error += objErr.StackTrace + "\n";

            if (error.IndexOf("文件不存在") < 0)
            {
                sw.WriteLine(DateTime.Now.ToString());
                sw.WriteLine(error); ;
            }
            sw.Close();
            sw.Dispose();
        }
复制代码

我们可以测试下。在项目中加入代码

复制代码
    <script language="C#" runat="server">
        void Page_Load(object sender, System.EventArgs e)
        {
            throw (new ArgumentNullException());
        }
    </script>
复制代码

运行(错误页面)

 

这是写入日志的信息errlog.txt
2012/8/20 15:43:58
发生异常页: http://localhost:2387/WebForm1.aspx
异常信息: 值不能为 null。
   在 ASP.webform1_aspx.Page_Load(Object sender, EventArgs e) 位置 f:\test2\login12\WebApplication1\WebApplication1\WebForm1.aspx:行号 10
   在 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   在 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
   在 System.Web.UI.Control.OnLoad(EventArgs e)
   在 System.Web.UI.Control.LoadRecursive()
   在 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

 

就算有了Application_Error,try...catch...还是需要的,为了精确定位错误的类型及信息,提出精确的提醒信息。写入日志的信息还可以根据自己的需要更改。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值