• ASP.NET 异常处理


    Asp.net开发过程中,我们会遇到很多Exception,不处理这些Exception的话会出现很难看的页面。
    还有一些我们未预料到的Exception,当发生Exception时,我们也必须进行记录具体位置,以便我们修正错误。
    asp.net
    异常处理的位置大概有以下3个地方
    1.
    程序的代码段中,这是最直接处理异常的地方。如下
    try
    {
        n=Convert.ToInt32(info);
    }
    catch(Exception)
    {
    }
    只是最基本处理异常的地方。

    2. ASP.NET的中的Application_Error.Application_Error 事件。对于应用程序中引发的任何未处理异常都会引发此事件。一般我们处理如下
    protected void Application_Error(Object sender, EventArgs e)
      {
        Exception exp=Server.GetLastError();
        string strE="
    内部错误:"+ exp.InnerException.ToString()+"\r\n堆栈:"+ exp.StackTrace+"\r "+"Message:"+exp.Message+"\r 来源:"+exp.Source;
       
       // 在事件日志中记录异常信息
       Log(strE);
       Server.ClearError();
       Server.Transfer("Error.aspx",false);
      }
    这样我们就可以处理Server端出现的错误。我们记录出错的源头。

    3. 也可以在页级别或者应用程序级别处理代码错误。Page 基类公开了一个 Page_Error 方法,此方法在页中可以被重写。每当运行时引发未捕获的异常时都调用此方法。
    void Page_Error(Object source, EventArgs e) {
        String message = "<font face=verdana color=red>"
            + "<h4>" + Request.Url.ToString() + "</h4>"
            + "<pre><font color='red'>"
            + Server.GetLastError().ToString() + "</pre>"
            + "</font>";

        Response.Write(message);
    }

     

    下面我讲述一下怎么在ASP.NET程序里面统一的处理异常,我们以最常见的Session过期为例

    我们先写一个Session过期的异常
    public class YSessionException:Exception
    {
    }

    我们再定义一个属性
    public int SessionValue
    {
         get{ if(Session["SessionValue"]==null)
                {
                    throw new YSessionException("");
                 }
              }
    }

    下面我们在Page_Error或者Application_Error中处理这个异常
      {
       Exception exp=Server.GetLastError();
                            if(exp is YSessionException)
                            {
                                   ..................
                            }
                            Server.ClearError();
       Server.Transfer("Error.aspx",false);
      }

    这样就可以为我们程序提供很好的Exception处理界面。

     

  • 相关阅读:
    Leetcode Binary Tree Level Order Traversal
    Leetcode Symmetric Tree
    Leetcode Same Tree
    Leetcode Unique Paths
    Leetcode Populating Next Right Pointers in Each Node
    Leetcode Maximum Depth of Binary Tree
    Leetcode Minimum Path Sum
    Leetcode Merge Two Sorted Lists
    Leetcode Climbing Stairs
    Leetcode Triangle
  • 原文地址:https://www.cnblogs.com/payne/p/754046.html
Copyright © 2020-2023  润新知