Asp. NET error handling (summary)

Source: Internet
Author: User
Tags finally block

Reprint to: http://www.cnblogs.com/chinhr/archive/2007/06/26/795947.html

Asp. NET error handling (Collation & Summary)
English Article research: http://wrfwjn.blog.hexun.com/4172839_d.html
General statement:
To create a global handler in a page, create a handler for the Page_Error event. To create an application-scoped error handler, add the code to the Application_Error method in the Global.asax file. These methods are called whenever an unhandled exception occurs in your page or application. You can get information about the latest error from the Httpserverutility.getlasterror method.
Note If you have a global error handler, it takes precedence over the error handling specified in the Defaultredirect property of the Web. config customErrors element.

principle (MSDN): When your application displays an error message, it should not divulge information that could help a malicious user to attack your system. For example, if your application tries to log on to the database without success, the error message that is displayed should not include the user name that it is using.

There are many ways to control error messages:

Configures the application to not display verbose error information to remote (application) users. You can also choose to redirect the error to the application page.
Include error handling whenever possible, and write your own error message. In your error handler, you can test to determine whether the user is a local user and respond accordingly.
Create a global error handler at the page level or application level that captures all unhandled exceptions and sends them to a generic error page. This way, even if you do not anticipate a problem, at least the user will not see the exception page.

< one > page-level error handling

{
String message="<font Face=verdana color=red>"
+""+Request.Url.ToString ()+""
+"<pre><font color= ' Red ' > " + server.getlasterror (). ToString ()  +  "</pre>"
                            +  </font> ;

    response.write (message);
    server.clearerror ();
}


Note: You access error information from the server by using the server object. In particular, the example obtains the requested URL from the request object, as well as the most recent error of the Server object (using the GetLastError method) and converts both to a string that the client can display. After writing the message variable to the client, remove the error by using the ClearError method

< two > application-level Error events , the error is handled as follows: Add processing logic to Application_Error in the Global.asax file to add other actions, such as writing to the Windows event log, sending an email to an administrator, Writes error information to the database. Specific as follows:

ProtectedvoidApplication_Error (Object sender, EventArgs e)
2{
3String 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 to the Windows event log
7String LogName="Application";
8If(!EventLog.SourceExists (LogName))
9{
10EventLog.CreateEventSource (LogName, LogName);
11}
12             EventLog Log  = new eventlog ();
13             log.source =  LogName;
14             log.writeentry (Message, eventlogentrytype.error);
15         }


< three >Web. config, custom error message . Configure the application to not display errors to remote users

CustomErrors mode="RemoteOnly"Defaultredirect="Apperrors.aspx">
<Error StatusCode="404"redirect=nosuchpage.aspx< Span style= "color: #000000;" > "/>&NBSP;
   <error statuscode= "403"  redirect= Noaccessallowed.aspx "/> &NBSP;
</>


Note: Set the Mode property to RemoteOnly (case sensitive). This configures the application to display detailed errors only to local users (you and developers).
Optionally, include the Defaultredirect property that points to the application error page.
(optional) includes the <error> element that redirects the error to a specific page. For example, you can redirect a standard 404 error (Page not found) to your own application page.

< four > including error handling (MSDN)
1. Use the try-catch-finally block before and after any statements that may produce errors.
2. (optional) Use the UserHostAddress property of the Context object to test the local user and modify the error handling accordingly. The value 127.0.0.1 is equivalent to "localhost" and instructs the browser to reside on the same computer as the WEB server.
A sample error handling block is shown below. If an error occurs, the session state variable is loaded with details about the message, and then the application displays a page that can read the session variable and display the error. (intentionally writing this error to not provide any available details to the user.) If the user is a local user, provide different error details. In the finally block, release the open resource.

Try
2{
3Sqlconnection1.open ();
4SqlDataAdapter1.Fill (DSCUSTOMERS1);
5}
6Catch(Exception ex)
7{
8If(HttpContext.Current.Request.UserHostAddress=="127.0.0.1")
9{session["Currenterror"]=Ex. Message; }
10Else
11{session["Currenterror"]="Error processing page."; }
12     server.transfer ( "applicationerror.aspx ");
13}
14finally&NBSP;
15< Span style= "color: #000000;" >{
16    this.sqlconnection1.close ();
17



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

In the process of ASP, we will encounter a lot of exception, if we do not deal with these exception, it will be difficult to see the page.
There are some exception that we do not anticipate, and when exception occurs, we must also record the exact location so that we can fix the error.
The location of the ASP. NET exception handling is approximately 3 places
1. In the code snippet of the program, this is the most straightforward place to handle the exception. As follows
Try
{
N=convert.toint32 (info);
}
catch (Exception)
{
}
Just the most basic handling of exceptions.

2. ASP. NET in the Application_Error. Application_Error event. This event is raised for any unhandled exception that is thrown in the application. Generally we deal with 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);
  }
This way we can handle errors that occur on the server side. We record the source of the error.

3. Code errors can also be handled at the page level or at the application level. The page base class exposes a Page_Error method that can be overridden in a page. This method is called whenever an uncaught exception is thrown by the runtime.
void Page_Error (Object source, EventArgs e) {
String message = "<font Face=verdana color=red>"
+ "+ "<pre><font color= ' Red ' >"
+ Server.GetLastError (). ToString () + "</pre>"
+ "</font>";

Response.Write (message);
}

Let me tell you how to handle exceptions uniformly in ASP, we take the most common session expiration as an example

Let's start by writing a session with an expired exception
public class Ysessionexception:exception
{
}

We define a property again
public int Sessionvalue
{
get{if (session["Sessionvalue"]==null)
{
throw new Ysessionexception ("");
}
}
}

Let's deal with this anomaly in Page_Error or Application_Error.
{
Exception Exp=server.getlasterror ();
if (exp is ysessionexception)
{
..................
}
Server.ClearError ();
Server.Transfer ("Error.aspx", false);
}

This will provide a good exception processing interface for our program.

Asp. NET error handling (summary)

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.