Error handling program

Source: Internet
Author: User

ASP. NET error handling methods (Collation & summary)
Research on http://wrfwjn.blog.hexun.com/4172839_d.html
Summary:
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 that 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 () + "</H4>"
+ "<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. Details: 1 protected void application_error (Object sender, eventargs E)
2 {
3 string message = "\ n \ nurl: \ n http: // localhost/" + request. Path
4 + "\ n \ nmessage: \ n" + server. getlasterror (). Message
5 + "\ n \ nstack trace: \ n" + server. getlasterror (). stacktrace;
6 // write windows Event Logs
7 string LOGNAME = "application ";
8 If (! EventLog. sourceexists (LOGNAME ))
9 {
10 EventLog. createeventsource (LOGNAME, LOGNAME );
11}
12 EventLog log = new EventLog ();
13 log. Source = LOGNAME;
14 log. writeentry (message, eventlogentrytype. Error );
15}

<3>Custom error information in Web. config. Configure the application to not display errors to remote users <customerrors mode = "remoteonly" defaultredirect = "apperrors. aspx">
<Error statuscode = "404" Redirect = "nosuchpage. aspx"/>
<Error statuscode = "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. 1try
2 {
3 sqlconnection1.open ();
4 sqldataadapter1.fill (dscustomers1 );
5}
6 catch (exception ex)
7 {
8 If (httpcontext. Current. Request. userhostaddress = "127.0.0.1 ")
9 {session ["currenterror"] = ex. Message ;}
10 else
11 {session ["currenterror"] = "error processing page .";}
12 server. Transfer ("applicationerror. aspx ");
13}
14 finally
15 {
16 this. sqlconnection1.close ();
17}

You can also create an error handler that captures all unprocessed exceptions at the page level or for the entire application.
============================

In the Asp.net development process, we will encounter many exceptions. If we do not handle these exceptions, there will be ugly pages.
There are also some unexpected exceptions. When an exception occurs, we must record the specific location so that we can correct the error.
Asp.net has the following three locations for exception handling:
1. In the code segment of the program, this is the most direct way to handle exceptions. As follows:
Try
{
N = convert. toint32 (Info );
}
Catch (exception)
{
}
Only the most basic exception handling.

2. application_error event in application_error in ASP. NET. This event is triggered for any unprocessed exceptions thrown in the application. Generally, we handle the following:
Protected void application_error (Object sender, eventargs E)
{
Exception exp = server. getlasterror ();
// Errorlog. Log (exp );
// ==============================================
String stre = "internal error:" + E. innerexception. tostring () + "\ r \ n Stack:" + E. stacktrace + "\ r" + "message:" + E. message + "\ r source:" + E. source;
Log (stre );
Server. clearerror ();
Server. Transfer ("error. aspx", false );
}
In this way, we can handle server errors. We record the source of the error.

3. Code errors can also be handled at the page or application level. The page base class exposes a page_error method, which can be overwritten on the page. This method is called whenever an uncaptured exception is thrown during running.
Void page_error (Object source, eventargs e ){
String message = "<font face = verdana color = Red>"
+ "<H4>" + request. url. tostring () + "</H4>"
+ "<PRE> <font color = 'red'>"
+ Server. getlasterror (). tostring () + "</PRE>"
+ "</Font> ";

Response. Write (Message );
}

 

The following describes how to handle exceptions uniformly in ASP. NET programs. We take the most common session expiration as an example.

Let's first write an exception about session expiration.
Public class ysessionexception: exception
{
}

Let's define another attribute.
Public int sessionvalue
{
Get {If (session ["sessionvalue"] = NULL)
{
Throw new ysessionexception ("");
}
}
}

Next we will handle this exception in page_error or application_error.
{
Exception exp = server. getlasterror ();
If (exp is ysessionexception)
{
..................
}
Server. clearerror ();
Server. Transfer ("error. aspx", false );
}

In this way, we can provide a good exception processing interface for our program.

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.