ASP. Displays the specified error page when a server error occurs

Source: Internet
Author: User
Tags stack trace

http://blog.csdn.net/helloxiaoyu/article/details/2943537

This article describes how to use C # when an exception occurs in ASP. NET code to intercept and corresponding exceptions. Asp. NET is superior to the traditional ASP in exception handling. In ASP. NET, exceptions are allowed to be handled at various levels of the application.
Asp. NET's new features
Asp. NET provides more convenience for capturing and handling exceptions. In traditional ASP programs, we use "on Error Resume Next" (or JScript Try-catch) to handle exceptions. Another way is if you run IIS5.0 and use the ASPError object to create a custom error page, however, these methods have their limitations.
When an ASP. NET application error occurs, ASP. NET provides some ways to capture and handle these exceptions. ASPNET provides three primary methods that allow you to catch and handle errors when an error occurs: The Page_Error event Application_Error event, and the application configuration file (Web. config)
This article is intended to demonstrate how to use these three new features in your ASPNET application. However, this article does not describe other exception handling methods, such as: Try-catch-finally, and CLR (Common Language Runtime) exception handling system.
How to use the Page_Error event
The Page_Error event provides a way to intercept page-level exceptions. You can simply display the error message (see example), or log in or perform other actions.
Note: This example shows how to display detailed error messages in the browser. Note that it is not a good idea to display detailed error messages to the user, especially when the application is running on the Internet. A more appropriate method is to display a message to the user informing them that an error occurred, The error details are then recorded in the log.
This example throws a null exception, forcing the exception to appear in the Page_Load event. Follow these steps to create a page that tests the Page_Error event.
Follow the steps below to create a new file named Pageevent.aspx in your project:

Open VisualStudio.NET

In the solution browser, right-click the project node, point to Add, and then click Add New Form.

In the Name text box, enter Pageeven.aspx, and then click Open.

Add the following code to the 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>

On the File menu, click Save.

Right-click the page, and then tap Browse in browser to run this page. The exception is thrown as we expected and is handled by the code above.

Note: You may notice that this code calls the Server.ClearError method. This method prevents the exception from being passed to the Application_Error event.
Also, you should note the Inherits property of the @page tag. If inherits is set, you should compile the entire project first, otherwise you will receive the following error message when you browse this page: ' Project.pageevent ' is not a valid type
How to use the Application_Error event
Similar to Page_Error, you can use the Application_Error event to intercept exceptions in your application because of the application-level scope of this event, you can log error messages into the logs or handle other application-level exceptions that may occur.
The following example originates from the Page_Error event code described above and is fired when the exception in the Page_Load event is not handled by the Page_Error event. The Application_Error event is specified in the Global.asax file. For simplicity, The following steps create a new page and throw an exception that intercepts and handles the exception in the Application_Error event in the Global.asax file and writes an error to the log. The following steps demonstrate how to use the Application_Error event:
Add a file named AppEvent.aspx to your project.
Add the following code to the AppEvent.aspx file:
<script language=c# runat= "Server" >
void Page_Load (object sender, System.EventArgs e)
{
Throw (new ArgumentNullException ());
}
</script>
<script language=c# runat= "Server" >
void Page_Load (object sender, System.EventArgs e)
{
Throw (new ArgumentNullException ());
}

</script>

Save.

Add Application_Error to the Global.asax file to intercept exceptions thrown in the apevent.aspx file. Note that You must add a reference to the System.Diagnostics namespace in the Global.asax file to use the event log.
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 ...
}

Save.

Compile.

Run

How to use the Web. config file
If you are not calling the Server.ClearError method or catching an exception in the Page_Error or Application_Error method, the exception will follow the Web. config file <customErrors> The messenger of the section is processed. In the <customErrors> section, you can specify a default error-guided page (defaultredirect) or specify a specific HTTP page error code. You can use this method to customize the error code that the user receives.

If the error is not captured at all levels of the application, the custom page is displayed. This section explains how to edit the Global.asax file to ensure that the Server.ClearError method is not called. Therefore, The exception is captured by the Web.congif file as the last loop exception handling method.
Open the Global.asax file for the previous example.
Comment out the Server.ClearError line.
Save, your code should look like the following code:
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 ...
}
Add the following code to redirect the user to the custom page:
<customerrors defaultredirect= "http://hostName/applicationName/errorStatus.htm"Mode=" on ">
</customErrors>
Note: You must modify the Defaultredirect property to associate your own application page.
Because the exception being intercepted at this level is sent to a default error page, you must create an error page and name it errorstatus.htm. Keep in mind that you are using this method to control what is presented to the user, so this example uses an HTML file to act as an error page. Add the following code to the errorstatus.htm file .<meta name= "GENERATOR" content= "Microsoft Visual Studio 7.0" >
</HEAD>
<BODY>
<b>custom Error page!</b>
<br>you has been redirected from the &lt;customErrors&gt; section of the Web. config file.</body> </HTML>
Save, compile the project, and then browse appevent.aspx in the browser to test the above code. Note that you will be redirected to the errorstatus.htm page when the exception is thrown
Although you can refer to a default error page by setting the Defaultredirect property of the <customErrors> section, youYou can also specify that the user is directed to a different page when a specific HTTP code exception appears .<error> child elements are used to set this function. Example:
<customerrors defaultredirect= "http://hostName/applicationName/errorStatus.htm" mode= "on" >
<error statuscode= "404" redirect= "filenotfound.htm"/>
</customErrors>
Note: The Defaultredirect property here is set to an HTML page. If you want to invoke the Server.GetLastError method in an ASPX file (like the example above Page_Error and Application_Error), You must store the exception in the session variable or other appropriate place before redirecting.
Notice that the <customErrors> sections includes a mode attribute that's set to on. The mode attribute is used-to-control how the error redirection occurs. For example, if you is developing the application, you have likely want to see the actual ASP error messages and do n OT want to being redirected to the more user-friendly error page. The mode attribute includes the following settings:
The <customErrors> section includes a mode property that is set to ON. This property is used to control the way the error is redirected. For example, if you are developing a Web application, you may want to see the actual aspenet error message, You don't want to be redirected to a good error page. This property includes the following settings:
On: An unhandled exception occurs when the user is redirected to the page of the Defaultredirect property setting. Most used in the product.
OFF: The user will be given a detailed error message and will not be redirected to the specified error page. This setting is mostly used in the development process.
RemoteOnly: The details of the exception can only be obtained when the local computer is accessed (localhost). Other users are redirected to the specified error page. Mainly used in the wrong process.

How to do C # in ASP. When uploading a file, you are prompted to upload the file too large to be able to

http://bbs.csdn.net/topics/380249577

The principle and implementation of Web upload file

Http://www.cnblogs.com/nokiaguy/archive/2008/05/29/1209858.html

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.