ASP. NET Error Handling Method

Source: Internet
Author: User
To create a global handler on the page, create a handler for the Page_Error event. To create an error handler within the application scope, add the code to the Application_Error method in the Global. asax file. These methods are called if an unhandled exception occurs on your page or application. You can obtain the latest error information from the HttpServerUtility. GetLastError method.
Note: If you have a global error handler, it takes precedence over the error handling specified in the defaultRedirect attribute of the customErrors element of Web. config.

Principles (msdn ):When your application displays an error message, it should not disclose information that helps malicious users attack your system. For example, if your application fails to log on to the database, the error message should not include the username in use.

There are many ways to control error messages:

Configure the application to not display detailed error messages to remote (Application) users. You can also redirect errors to the application page.
If it is feasible, it includes error handling and compiling your own error information. In your error handling program, you can perform a test to determine whether the user is a local user and respond accordingly.
Create a global error handler at the page or application level that captures all unprocessed exceptions and sends them to the general error page. In this way, even if you do not anticipate a problem, at least the user will not see the exception page.

<1> page-Level Error Handling

Void Page_Error (Object sender, EventArgs e ){
String message = "<font face = verdana color = red>"
+ "<H4>" + Request. Url. ToString () + "+ "<Pre> <font color = 'red'>" + Server. GetLastError (). ToString () + "</pre>"
+ "</Font> ";

Response. Write (message );
Server. ClearError ();
Note: Access Error messages from the Server by using the Server object. In particular, this example gets the Request URL from the Request object and the latest error of the Server object (using the GetLastError method), and converts both to strings that can be displayed by the client. After writing the message variable to the client, use the ClearError method to delete the error.

<2> application-level error eventsThe error handling method is as follows: add processing logic to application_error in the global. asax file. You can add other operations, such as writing windows event logs, sending emails to administrators, and writing error information to the database. The details are as follows:

Protected void Application_Error (Object sender, EventArgs e)
{
String Message = "\ n \ nURL: \ n http: // localhost/" + Request. Path
+ "\ N \ nMESSAGE: \ n" + Server. GetLastError (). Message
+ "\ N \ nSTACK TRACE: \ n" + Server. GetLastError (). StackTrace;
// Write windows Event Logs
String LogName = "Application ";
If (! EventLog. SourceExists (LogName ))
{
EventLog. CreateEventSource (LogName, LogName );
}
EventLog Log = new EventLog ();
Log. Source = LOGNAME;
Log. writeentry (message, eventlogentrytype. Error );
}
<3>Custom error information in web. config. Configure the application to not display errors to remote users

<CustomerrorsMode = "remoteonly"Defaultredirect = "apperrors. aspx">
<ErrorStatuscode = "404"Redirect = "nosuchpage. aspx"/>
<ErrorStatuscode = "403"Redirect = "noaccessallowed. aspx"/>
</Customerrors>

Note: Set the mode attribute to remoteonly (case sensitive ). This configures the application to display detailed errors only to local users (you and developers.
Optional. includes the defaultredirect attribute pointing to the application error page.
(Optional) includes the <error> element that redirects an error to a specific page. For example, you can redirect standard 404 errors (page not found) to your own application page.

<4>Including error handling (MSDN)
1. Use try-catch-finally blocks before and after any statements that may produce errors.
2. (optional) use the userhostaddress attribute of the context object to test the local user and modify the error accordingly. The value 127.0.0.1 is equivalent to "localhost" and instructs the browser and web server to be on the same computer.
The following shows an example of error handling block. If an error occurs, load the session state variable with detailed information about the message. Then, the application shows that the session variable can be read and the error page is displayed. (Intentionally write this error so that you are not provided with any details available .) If the user is a local user, different error details are provided. Release open resources in finally blocks.
Try
{
Sqlconnection1.open ();
Sqldataadapter1.fill (dscustomers1 );
}
Catch (exception ex)
{
If (httpcontext. Current. Request. userhostaddress = "127.0.0.1 ")
{Session ["currenterror"] = ex. Message ;}
Else
{Session ["currenterror"] = "error processing page .";}
Server. Transfer ("applicationerror. aspx ");
}
Finally
{
This. sqlconnection1.close ();
}

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.