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