Create a custom error report page in ASP. NET

Source: Internet
Author: User
This page Summary

New functions in ASP. NET

How to Use the page_error event

How to Use the application_error event

How to use the Web. config file Summary

This article describes how to use Visual Basic. net when an error occurs in ASP. NET.CodeCapture and respond to errors. ASP. NET has improved the error handling options based on the traditional Microsoft Active Server Pages (ASP. In ASP. NET, you canProgram.

New functions in ASP. NET


ASP. NET has made several improvements in handling and responding to errors. In traditional ASP, "On Error resume next" (or in JScript) is used.Try-catchBlock. Alternatively, if you are running Microsoft Internet Information Service (IIS) 5.0, useAsperrorCreate a custom error report page for the object. 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_errorEvents,Application_errorEvent and application configuration file (Web. config ).

This article demonstrates how to use these new features in ASP. NET applications. Although this article describes how to provide custom error pages and common error reports because it is directly related to ASP. NET, it does not introduce other error handling methods, suchTry-catch-finallyBlock and Common Language Runtime Library (CLR) exception system.

How to Use the page_error event

Page_errorEvents provide a way 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.

Remarks: 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 occurs inPage_loadNull exception in the event. Follow these steps to create and TestPage_errorThe initial Page of the 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 and pointAddAnd then clickAdd a web form.
C. InNameIn the text box, typePageevent. aspxAnd then clickOpen.
2. Add the following code to pageevent. in aspx:

 <% @ page Language = "VB" %>  

3. SlaveFileIn the menu, clickSave pageevent. aspx.
4. Right-click the page, and then clickView in a browserTo run the page. Please note that errors will be thrown and reported according to code specifications.

Remarks: You may notice that the code sendsServer. clearerror. This will prevent the error from continuing to be processedApplication_errorEvent.

 How to Use the application_error event


AndPage_errorThe event is similar, you can useApplication_errorAn error occurs 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 previousPage_errorEvent code example, ifPage_loadThe error in the event is notPage_errorEvent is captured, and an exception is thrown.Application_errorThe 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 is to be thrown and captureApplication_errorAnd write the error to the event log. The following steps demonstrate how to useApplication_errorEvent:

1. Add a new file named appevent. aspx to the project:
2. Add the following code to appevent. aspx:

<Script language = VB runat = "server"> sub page_load (sender as object, e as eventargs) Throw (New argumentnullexception () end sub </SCRIPT>

3. SlaveFileIn the menu, clickSave appevent. aspx.
4. Set Application_error Events are added to the global. asax file to capture Page_load Errors in the event. Note that you must System. Diagnostics Namespace Imports Add the statement to global. asax of the event log to be used.

Add the following code to the Global. asax file:

Imports system. diagnostics sub application_error (byval sender as object, byval e as eventargs) dim objerr as exception = server. getlasterror (). getbaseexception () dim err as string = "error caught in application_error event" & _ system. environment. newline & _ "error in:" & request. URL. tostring () & _ system. environment. newline & _ "error message:" & objerr. message. tostring () & _ system. environment. newline & _ "stack trace:" & objerr. stacktrace. tostring () EventLog. writeentry ("sample_webapp", err, eventlogentrytype. error) server. clearerror () 'additional actions... end sub

5. Save the global. asax file.
6. In Visual Studio. NETGenerateClickGenerate.
7. Right-click the page, and then clickView in a 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 callServer. clearerrorOr capturePage_errorOrApplication_errorErrors in the event are handled according to the settings 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 specify 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 you can never callServer. clearerror. 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. SetServer. clearerrorLine comment out to make sure the error appears in the web. config file.
3. Save the changes to global. asax. The code should look like the following:

 sub application_error (byval sender as object, byval e as eventargs) dim objerr as exception = server. getlasterror (). getbaseexception () dim err as string = "error caught in application_error event" & _ system. environment. newline & _ "error in:" & request. URL. tostring () & _ system. environment. newline & _ "error message:" & objerr. message. tostring () & _ system. environment. newline & _ "stack trace:" & objerr. stacktrace. tostring () EventLog. writeentry ("sample_webapp", err, eventlogentrytype. error) 'server. clearerror () 'additional actions... end sub 

4. Add the following code to the section to redirect the user to the custom page:

 
        
        

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

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 canDefaultredirectThe default error page is referenced in the attribute value, but you can 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>

Remarks: In the <customerrors> sectionDefaultredirectThe specified page is a. htm file. If you want to useGetlasterror(Page_errorAndApplication_errorIn this example, the exception must be stored in the session variable or another method before redirection.

Note that the <customerrors> section includesOnOfModeAttribute.ModeAttribute 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.ModeAttributes include the following settings:

On: Unhandled exceptions redirect users to the specifiedDefaultredirectPage. This mode is mainly used for production.
Off: The user receives the exception message instead of being redirectedDefaultredirectPage. This mode is mainly used for development.
Remoteonly: The exception message can only be received by the user accessing the site on the Local Computer (by using localhost. All other users are redirectedDefaultredirectPage. This mode is mainly used for debugging.
Troubleshooting


In the default installation on Windows 2000 and Windows XP, ASP. NET runs web application code in the auxiliary process. By default, the process ID is an unprivileged local account named ASPnet. In ASP. NET beta, the Process Identity is system, which is a powerful Administrator account with many computer privileges.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.