常见的处理异常方式有两种:
1.Web.config
2.Application_Error
这两种就不多说了,网上非常多

但可能是C/S的程序写多了,有时总觉得用着不舒服,因此想把换个自已认为舒服点的方式处理异常。
前提:使用了MasterPage

1.在MasterPage中输入以下代码:

1        internal void ShowError(Exception ex)
2        {
3            Session.Add("Exception", ex);
4            Response.Redirect("Error.aspx");
5        }

2.Error.aspx.cs中输入以下代码:

 1        protected void Page_Load(object sender, EventArgs e)
 2        {
 3            if (Session["Exception"!= null)
 4            {
 5                Exception ex = Session["Exception"as Exception;
 6
 7                if (ex != null)
 8                {
 9                    this.lblErrMsg.Text = ex.Message;
10                }

11                else
12                {
13                    this.lblErrMsg.Text = "发生未知错误";
14                }

15
16                Session.Remove("Exception");
17            }

18            else
19            {
20                Response.Redirect("Default.aspx");
21            }

22        }

3.如果你有可能使用MasterPage的嵌套,那么可能需要(如果你不介意使用Master.Master...那么就不需要了)使用这样一个类型,姑且称之为:MasterHelper吧,代码如下:

 1        internal static T GetParentMaster<T>(MasterPage master)
 2          where T : MasterPage
 3        {
 4            MasterPage masterPage = null;
 5
 6            if (master is T)
 7            {
 8                masterPage = master;
 9            }

10
11            if (master != masterPage && master != null && master.Master != null)
12            {
13                masterPage = master.Master;
14
15                while ((masterPage is T) == false)
16                {
17                    masterPage = masterPage.Master;
18                }

19            }

20
21            return masterPage as T;
22        }

4.最后,捕获并处理异常:

1            try
2            {
3                throw new Exception("这是一个测试异常");
4            }

5            catch (Exception ex)
6            {
7                MasterHelper.GetMaster<MasterPage_FullName>(this.Master).ShowError(ex);
8            }

这个方法也许很C/S,能用的上的就凑合着用吧:)


 

posted on 2008-06-24 00:38  think8848  阅读(312)  评论(0编辑  收藏  举报