C # is a common language. Here we mainly introduce the C # application_error event, including the page_error event.
Similar to the page_error event, you can use the C # application_error event to captureProgram. 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 page_error event.CodeFor example, if an error in the page_load event is not captured in the page_error event, an exception is thrown. The C # 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 exceptions are to be thrown, capture errors in the C # application_error event of the global. asax file, and write the errors to the event log.
The following steps demonstrate how to use the C # application_error event:
Add a new file named appevent. aspx to the project, add the following code to appevent. aspx, and click Save appevent. aspx from the File menu. 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)
-
- {
-
- ExceptionObjerr=Server. Getlasterror (). getbaseexception ();
-
- StringErr="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...
-
- }
Save the global. asax file. In Visual Studio. NET, click Generate on the generate menu. 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.
If you do not call server. clearerror or capture an error in the page_error or C # application_error event, the error is handled based on the settings in the web. config file. In this 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.