Asp. NET error handling mechanism (concept)

Source: Internet
Author: User

In the case of Web applications, unpredictable errors and exceptions are unavoidable, and we must provide error handling mechanisms for Web programs. When the error occurs, we must do two things: one is to log the error message, email the site maintenance staff, convenient for technical personnel to track the error; the second is to prompt the end user page in a friendly way to make an error and not to display the unhandled error message to the user.

Let's think about it, ASP. NET provides us with several error-handling mechanisms? Do they have a certain priority if they are used at the same time? NET provides four error handling mechanisms that have a certain priority order: Page_Error event >errorpage Properties >application_error events > <customErrors> configuration Items. The usage of these four error handling mechanisms is described below.

1.page_error Events
The Page_Error event provides a way to capture errors that occur at the page level. You can just display an error message (as shown in the following example code), or you can log an event or perform some other action.
private void Page_Load (object sender, System.EventArgs e)
{
Put user code to initialize the page here
throw new Exception ("page error!");
}

protected void Page_Error (object sender, EventArgs e)
{
Exception objerr = Server.GetLastError (). GetBaseException ();
Response.Write ("Error:" + objerr.message);
Server.ClearError (); Also pay attention to the use of this Code
Note: This example displays detailed error information in the browser for illustrative purposes only. Be careful when displaying detailed information to end users of your application. It is more appropriate to display a message to the user informing that an error has occurred, and then record the specific error details in the log.

2.ErrorPage Properties
You can set the ErrorPage property almost at any time of the page to determine which page will be redirected to when the page error occurs. For the ErrorPage property to work,<customerrors> the Mode property in the configuration item must be set to "on".
This. ErrorPage = "~/errorhandling/pageerror.html";
If Page_Error and ErrorPage are present, what is the order of the page execution when the exception is thrown? The page executes the Page_Error event handler first, and if the Page_Error () event calls the function Server.ClearError () Clears the exception information, it does not jump to the ErrorPage property specified page If Server.ClearError () is not called, the exception information continues to be thrown up, and the page jumps to the ErrorPage specified page. This also proves the priority order: Page_Error event >errorpage property.

3.application_error Events
Similar to the Page_Error event, you can use the Application_Error event to capture errors that occur in your application. Because events occur throughout the application scope, you can log application error messages or handle other application-level errors that may occur. It is OK to add the following code to the Global.asax file.
protected void Application_Error (object sender, EventArgs e)
{
Exception ex = Server.GetLastError (). GetBaseException ();
In real-world applications, exception information can be recorded in log or stored in a database.
You can also send errors to the site maintenance staff
Response.Write ("Error:" + ex.) Message);
Clear exception to avoid continued delivery to the upper level of processing
The superior is the <CustomerErrors> configuration section here.
Server.ClearError ();
}
4.<customerrors> Configuration Items
The <customErrors> configuration section in configuration file Web. config, you can specify the redirect page as the default error page defaultredirect or specify a specific page based on the HTTP error code that is raised. This custom page is displayed if an error occurs that was not caught at any previous level of the application.
<customerrors mode= "on" defaultredirect= "~/errorhandling/applicationerror.html" >
<error statuscode= "404" redirect= "~/errorhandling/404.html"/>
</customErrors>
Similarly, if Application_Error and <customerErrors> exist at the same time, there is an issue of order of execution. Because of the priority Application_Error event > <customErrors> configuration Item, when an application-level error occurs, the code in the Application_Error event is first executed if Application_ The Server.ClearError () function called in the Error event,<customererrors> the defaultredirect in the configuration section does not work because exception has been cleared; The Server.ClearError () function is not called in the _error event, and the error page is relocated to the URL page specified defaultredict to display a friendly error message for the user.

through to. NET provides the above four kinds of error handling mechanism analysis, we can classify them from different angle, is easy for us to understand and use.
1. Functionally categorized: For exception handling (handling Exceptions) is Page_Error event and Application_Error event; User error page redirection (redirecting the user to an error Page) is the ErrorPage property and the <customErrors> configuration item.
2. Classification from error handling: Page_Error event and ErrorPage attribute for page level error handling, Application_Error event for application level (application) error handling and <customErrors> configuration items.

Note that the,<customerrors> section includes the Mode property set to ON. The Mode property is used to control how error redirection occurs. For example, if you are developing an application, you will most likely want to see the actual ASP. NET error message, and you do not want to be redirected to a more user-friendly error page. The Mode property includes the following settings:? On: Unhandled exception redirects the user to the specified defaultredirect page. This mode is mainly used for production.
? OFF: The user receives the exception information instead of being redirected to the defaultredirect page. This mode is primarily used for development.
? RemoteOnly: Only users who access the site on the local computer (by using localhost) can receive the exception information. All other users are redirected to the defaultredirect page. This mode is primarily used for debugging.

Asp. NET error handling mechanism (concept)

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.