There are two common exception handling methods:
1. Web. config
2. Application_Error
There are a lot of Internet
However, it may be that the C/S program is too much written, and sometimes it is uncomfortable to use, so I want to change the way I think it is comfortable to handle exceptions.
Prerequisite: MasterPage is used.
1. Enter the following code in MasterPage:
1 internal void ShowError (Exception ex)
2 {
3 Session. Add ("Exception", ex );
4 Response. Redirect ("Error. aspx ");
5}
2. Enter the following code in 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 = "Unknown error ";
14}
15
16 Session. Remove ("Exception ");
17}
18 else
19 {
20 Response. Redirect ("Default. aspx ");
21}
22}
3. if you may use MasterPage nesting, you may need to (if you don't mind using the Master. master... so you don't need to) use this type, for example, MasterHelper. The Code is as follows:
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. Finally, capture and handle exceptions:
1 try
2 {
3 throw new Exception ("this is a test Exception ");
4}
5 catch (Exception ex)
6 {
7 MasterHelper. GetMaster <MasterPage_FullName> (this. Master). ShowError (ex );
8}
This method may be very C/S. You can use it if you can use it :)