ASP. NET custom error page

Source: Internet
Author: User

 

ASP. NET provides three main methods for capturing and responding to errors when an error occurs: Page_Error event, Application_Error event, and application configuration file (Web. config ).

 

If you do not call Server. ClearError or capture an error in the Page_Error or Application_Error event, the error is handled based on the setting in the <customErrors> section of the Web. config file. In the <customErrors> section, you can specify the redirection page as the default error page (defaultRedirect) or a specific page based on the HTTP Error code. You can use this method to customize the error message you receive.

Although you can reference the default error page in the value of the defaultRedirect attribute in the <customErrors> section, you can also specify the specific page to be redirected Based on the HTTP Error code. <Error> this option is allowed for child elements.

<CustomErrors mode = "On" defaultRedirect = "ApplicationErroy. aspx">

<Error statusCode = "403" redirect = "403.htm"/>

<Error statusCode = "404" redirect = "404.htm"/>

<Error statusCode = "500" redirect = "500.htm"/>

</CustomErrors>

 

Asp.net custom error handling PAGE method 1

1. Add <customErrors mode = "On" to Web. config and <system. web> </system. web>"

DefaultRedirect = "ApplicationErroy. aspx"> </customErrors> node,

2. add error handling page: ApplicationErroy. aspx calls the following method:

Private void DealErroy ()

{

HttpException erroy = new HttpException ();

String strCode = erroy. ErrorCode. ToString ();

String strMsg = erroy. Message;

Erroy. HelpLink = "sss ";

Response. Write ("ErrorCode:" + strCode + "<br> ");

Response. Write ("Message:" + strMsg + "<br> ");

Response. Write ("HelpLink:" + erroy. HelpLink + "<br> ");

Response. Write ("Source:" + erroy. Source + "<br> ");

Response. Write ("TargetSite:" + erroy. TargetSite + "<br> ");

Response. Write ("InnerException:" + erroy. InnerException + "<br> ");

Response. Write ("StackTrace:" + erroy. StackTrace + "<br> ");

Response. Write ("GetHtmlErrorMessage:" + erroy. GetHtmlErrorMessage () + "<br> ");

Response. Write ("erroy. GetHttpCode (). ToString ():" + erroy. GetHttpCode (). ToString () + "<br> ");

Response. Write ("erroy. Data. ToString ():" + erroy. Data. ToString () + "<br> ");

}

 

Private void DealErroy ()

{

HttpException erroy = new HttpException ();

String strCode = erroy. ErrorCode. ToString ();

String strMsg = erroy. Message;

Erroy. HelpLink = "sss ";

Response. Write ("ErrorCode:" + strCode + "<br> ");

Response. Write ("Message:" + strMsg + "<br> ");

Response. Write ("HelpLink:" + erroy. HelpLink + "<br> ");

Response. Write ("Source:" + erroy. Source + "<br> ");

Response. Write ("TargetSite:" + erroy. TargetSite + "<br> ");

Response. Write ("InnerException:" + erroy. InnerException + "<br> ");

Response. Write ("StackTrace:" + erroy. StackTrace + "<br> ");

Response. Write ("GetHtmlErrorMessage:" + erroy. GetHtmlErrorMessage () + "<br> ");

Response. Write ("erroy. GetHttpCode (). ToString ():" + erroy. GetHttpCode (). ToString () + "<br> ");

Response. Write ("erroy. Data. ToString ():" + erroy. Data. ToString () + "<br> ");

}

 

This method cannot completely display the error message;

 

 

Asp.net custom error handling PAGE method 2

1. Add <customErrors mode = "On" to Web. config and <system. web> </system. web>"

DefaultRedirect = "ApplicationErroy. aspx"> </customErrors> node,

2. Add the Global. asax file, locate the Application_Error event, and add the following code:

// This is the addition of a global application class to handle error pages in Application_Error events and web. config. The error page can be located even if there is no web. config.

Void Application_Error (object sender, EventArgs e)

{

// Code that runs when an unhandled error occurs

Exception erroy = Server. GetLastError ();

String err = "error page:" + Request. Url. ToString () + "</br> ";

Err + = "exception information:" + erroy. Message + "</br> ";

Err + = "Source:" + erroy. Source + "</br> ";

Err + = "StackTrace:" + erroy. StackTrace + "</br> ";

// Clear the previous exception

Server. ClearError ();

// This process uses Session ["ProError"] error. So Application ["ProError"]

Application ["erroy"] = err;

// Response. Redirect ("../frmSysError. aspx") is not used in the page ");

System. Web. HttpContext. Current. Response. Redirect (HttpContext. Current. Request. ApplicationPath + "/ApplicationErroy. aspx ");

}

2. Add the following code to the error handling page: ApplicationErroy. aspx;

Protected void Page_Load (object sender, EventArgs e)

{

// Display the error codes in the program

If (! IsPostBack)

{

// Display the error codes in the program

If (Application ["erroy"]! = Null)

{

Response. Write (Application ["erroy"]. ToString ());

}

}

}

This method can completely Display Error information,

The best way is to use the two methods together!

In addition, you can also set

<CustomErrors mode = "On" defaultRedirect = "ApplicationErroy. aspx">

<Error statusCode = "403" redirect = "403.htm"/>

<Error statusCode = "404" redirect = "404.htm"/>

<Error statusCode = "500" redirect = "500.htm"/>

</CustomErrors>

 

Add

Http Error Code Description:

"403": Forbidden

"404": Not Found

"500": Internal Server Error

Http Error code meaning Daquan detailed explanation http://blog.ccidnet.com/blog-htm-do-showone-uid-36307-type-blog-itemid-4857876.html

 

 

Method 3 Page_Error event

The Page_Error event provides a method to capture page-level errors. You can only Display error messages (as shown in the following sample code), or record events or perform other operations.

Note: This example displays detailed error information in the browser. This example is only for instructions. Be careful when displaying detailed information (especially when the application is running on the Internet) to the end user of the application. A more appropriate way is to display a message to the user, tell the user that an error has occurred, and then record the detailed error information in the event log.

In this example, an empty error occurs in the Page_Load event. Follow these steps to create an initial page that will test the Page_Error event. 1. Follow these steps to add a new file named PageEvent. aspx to the project: a. Open Microsoft Visual Studio. NET.

B. In Solution Explorer, right-click the project node, point to add, and click Add Web form.

C. In the Name text box, type PageEvent. aspx and click open.

Add the following code to PageEvent. aspx:

<Script language = C # runat = "server">

Void Page_Load (object sender, System. EventArgs e)

{

Throw (new ArgumentNullException ());

}

Public void Page_Error (object sender, EventArgs e)

{

Exception objErr = Server. GetLastError (). GetBaseException ();

String err = "<B> Error Caught in Page_Error event </B>

"<Br> <B> Error in: </B>" + Request. Url. ToString () +

"<Br> <B> Error Message: </B>" + objErr. Message. ToString () +

"<Br> <B> Stack Trace: </B> <br>" +

ObjErr. StackTrace. ToString ();

Response. Write (err. ToString ());

Server. ClearError ();

}

</Script>

From the File menu, click Save PageEvent. aspx.

Right-click the page and click View in the browser to run the page. Please note that errors will be thrown and reported according to code specifications.

Note: You may notice that the Code calls Server. ClearError. This prevents the error from continuing to the Application_Error event to be processed.

Note the Inherits attribute in the @ Page command. If you have set Inherits, you must first generate the project and then browse to the page. If the Project is not generated first, the following error message is displayed: 'Project. pageevent' is not a valid type

(Transfer)

ASP. NET has made several improvements in handling and responding to errors. In traditional ASP, "On Error Resume Next" (or try-catch Block in Jscript) is used to handle errors. Alternatively, if you are running Microsoft Internet Information Services (IIS) 5.0, use the ASPError object to create a custom error report page. However, these methods have their own limitations.

ASP. NET provides several processing and response levels for errors that may occur when running ASP. NET applications. ASP. NET provides three main methods for capturing and responding to errors when an error occurs: Page_Error event, Application_Error event, and application configuration file (Web. config ).

This article demonstrates how to use these new features in ASP. NET applications. Despite.. NET directly introduces how to provide custom error pages and general error reports, but it does not introduce other error handling methods, for example, try-catch-finally blocks and CLR abnormal systems.

How to Use the Page_Error event

The Page_Error event provides a method to capture page-level errors. You can only Display error messages (as shown in the following sample code), or record events or perform other operations.

Note: This example displays detailed error information in the browser. This example is only for instructions. Be careful when displaying detailed information (especially when the application is running on the Internet) to the end user of the application. A more appropriate way is to display a message to the user, tell the user that an error has occurred, and then record the detailed error information in the event log.

In this example, an empty error occurs in the Page_Load event. Follow these steps to create an initial page that will test the Page_Error event. 1. Follow these steps to add a new file named PageEvent. aspx to the project: a. Open Microsoft Visual Studio. NET.

B. In Solution Explorer, right-click the project node, point to add, and click Add Web form.

C. In the Name text box, type PageEvent. aspx and click open.

2. Add the following code to PageEvent. aspx:

<Script language = C # runat = "server">

Void Page_Load (object sender, System. EventArgs e)

{

Throw (new ArgumentNullException ());

}

Public void Page_Error (object sender, EventArgs e)

{

Exception objErr = Server. GetLastError (). GetBaseException ();

String err = "<B> Error Caught in Page_Error event </B>

"<Br> <B> Error in: </B>" + Request. Url. ToString () +

"<Br> <B> Error Message: </B>" + objErr. Message. ToString () +

"<Br> <B> Stack Trace: </B> <br>" +

ObjErr. StackTrace. ToString ();

Response. Write (err. ToString ());

Server. ClearError ();

}

</Script>

3. From the File menu, click Save PageEvent. aspx.

4. Right-click the page and click View in the browser to run the page. Please note that errors will be thrown and reported according to code specifications.

Note: You may notice that the Code calls Server. ClearError. This prevents the error from continuing to the Application_Error event to be processed.

Note the Inherits attribute in the @ Page command. If you have set Inherits, you must first generate the project and then browse to the page. If the Project is not generated first, the following error message is displayed: 'Project. pageevent' is not a valid type

How to Use the Application_Error event

Similar to the Page_Error event, you can use the Application_Error event to capture errors that occur in the application. As events occur throughout the application, you can record application error messages or handle other possible application-level errors.

The following example is based on the previous code example of the Page_Error event. If an error in the Page_Load event is not captured in the Page_Error event, an exception is thrown. The Application_Error event is specified in the Global. asax file of the application. For simplicity, the steps in this section create a new page in which an exception will be thrown, capture the error in the Application_Error event of the Global. asax file, and write the error to the event log. The following steps demonstrate how to use the Application_Error event: 1. Add a new file named AppEvent. aspx to the project:

2. Add the following code to AppEvent. aspx:

<Script language = C # runat = "server">

Void Page_Load (object sender, System. EventArgs e)

{

Throw (new ArgumentNullException ());

}

</Script>

3. From the File menu, click Save AppEvent. aspx.

4. Add the Application_Error event to the Global. asax file to capture the error caused by the Page_Load event on the AppEvent. aspx page. Note: you must add another using statement to Global. asax for the System. Diagnostics namespace to use Event Logs.

Add the following code to the Global. asax file:

Using System. Diagnostics;

Protected void Application_Error (object sender, EventArgs e)

{

Exception objErr = Server. GetLastError (). GetBaseException ();

String err = "Error Caught in Application_Error event \ n" +

"Error in:" + Request. Url. ToString () +

"\ NError Message:" + objErr. Message. ToString () +

"\ NStack Trace:" + objErr. StackTrace. ToString ();

EventLog. WriteEntry ("Sample_WebApp", err, EventLogEntryType. Error );

Server. ClearError ();

// Additional actions...

}

5. Save the Global. asax file.

6. In Visual Studio. NET, click Generate on the generate menu.

7. Right-click the page and click View in the browser. In this case, the page will be blank, but you should note that a new item has been added to the event log. In this example, an item is generated in the Application Log to access the application log from the event viewer. After an error is recorded, you may want to redirect the user to another user-friendly error page or perform other operations as needed.

 

How to use the Web. config file

If you do not call Server. ClearError or capture an error in the Page_Error or Application_Error event, the error is handled based on the setting in the <customErrors> section of the Web. config file. In the <customErrors> section, you can specify the redirection page as the default error page (defaultRedirect) or a specific page based on the HTTP Error code. You can use this method to customize the error message you receive.

If an error is not captured at any level before the application, this custom page is displayed. This section describes how to modify the Global. asax file so that Server. ClearError is never called. Therefore, the error is processed in the Web. config file that is the last point to capture the error. 1. Open the Global. asax file from the previous example.

2. comment out the Server. ClearError line to ensure that the error appears in the Web. config file.

3. Save the changes to Global. asax. The code should look like the following:

Using System. Diagnostics;

Protected void Application_Error (object sender, EventArgs e)

{

Exception objErr = Server. GetLastError (). GetBaseException ();

String err = "Error Caught in Application_Error event \ n" +

"Error in:" + Request. Url. ToString () +

"\ NError Message:" + objErr. Message. ToString () +

"\ NStack Trace:" + objErr. StackTrace. ToString ();

EventLog. WriteEntry ("Sample_WebApp", err, EventLogEntryType. Error );

// Server. ClearError ();

// Additional actions...

}

4. Add the following code to the <customErrors> section to redirect users to the custom page:

<CustomErrors defaultRedirect = "errorStatus.htm" mode = "On">

</CustomErrors>

Note: You must modify the file path in the defaultRedirect attribute so that it references the relevant Web server and Application name.

5. Create an error page named errorstatus.htm for the error message sent to the sender due to the error caught at this level. Please use this document to control the content presented to the user. For this example, use the .htm page as the error page. Migrate the following code to errorstatus.htm:

<HTML>

<HEAD>

<TITLE> </TITLE>

<Meta name = "GENERATOR" Content = "Microsoft Visual Studio 7.0">

</HEAD>

<BODY>

<B> Custom Error page! </B>

<Br>

You have been redirected here from the <customErrors> section of

Web. config file.

</BODY>

</HTML>

6. To test the code, save these files, generate a project, and view AppEvent. aspx in the browser. Please refer to the following link to the error code: errorstatus.htm.

Although you can reference the default error page in the value of the defaultRedirect attribute in the <customErrors> section, you can also specify the specific page to be redirected Based on the HTTP Error code. <Error> this option is allowed for child elements. For example:

<CustomErrors defaultRedirect = "errorStatus.htm" mode = "On">

<Error statusCode = "404" redirect = "filenotfound.htm"/>

</CustomErrors>

Note: In the defaultRedirect section of <mermerrors>, the page is a. htm file. If you plan to use GetLastError (as shown in the Page_Error and Application_Error examples) on the. aspx page, you must store exceptions in session variables or some other methods before redirection.

Note that the <customErrors> section includes the mode attribute set to On. The mode attribute is used to control how error redirection occurs. For example, if you are developing an application, you may want to view the actual ASP. NET error information and do not want to be redirected to a more user-friendly error page. The mode attribute includes the following settings :? On: unhandled exceptions redirect users to the specified defaultRedirect page. This mode is mainly used for production.

? Off: the user receives the exception message instead of being redirected to the defaultRedirect page. This mode is mainly used for development.

? RemoteOnly: only the user accessing the site on the Local Computer (by using localhost) can receive exception information. All other users are redirected to the defaultRedirect page. This mode is mainly used for debugging.

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.