ASP. NET custom error page

Source: Internet
Author: User

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 the ability to run ASP. NET applications.ProgramPossible error handling and response levels. 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 the error message (as shown in the following example)CodeYou can also record events or perform some 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, a forced error is thrown 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:

Public void page_error (Object sender, eventargs e)
{< br> exception objerr = server. getlasterror (). getbaseexception ();
string err = " error caught in page_error event


" +
"
error in: "+ request. URL. tostring () +
"
error message: " + objerr. message. tostring () +
"
stack trace:
" +
objerr. stacktrace. tostring ();
response. write (err. Tostring ();
server. clearerror ();
}< br>
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)
{< br> 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, eventlogentr Ytype. error);
server. clearerror ();
// additional actions...
}< br>
5. save 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 = "http: // hostname/applicationname/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. Because errors captured at this level are sent to the default error page, you must create an error page named errorstatus.htm. Remember, you need to use this method to control the content presented to the user, so this example uses the. htm page as the error page. Add 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 & lt; customerrors & gt; 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. Note that when an error is thrown, you will be redirected to the errorstatus.htm page.
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 = "http: // hostname/applicationname/errorstatus.htm" mode = "on">
<Error statuscode = "404" Redirect = "filenotfound.htm"/>
</Customerrors>
Note: The page specified in defaultredirect in the <customerrors> section 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.

Related Article

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.