[原]ASP.NET處理異常的另一種方式

來源:互聯網
上載者:User

常見的處理異常方式有兩種:
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,能用的上的就湊合著用吧:)

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.