[Original] Another way for ASP. NET to handle exceptions

Source: Internet
Author: User

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 :)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.