Page error handling
ASP. NET provides two levels of global exception interception points, respectively at the page level and application level.
A base-class page exposes an error event, which can be rewritten on the page to capture unprocessed exceptions caused during page execution.
There is also an error event in the httpapplication class, which is used to capture all the unprocessed exceptions thrown in the entire application.
Page-Level Error Handling
To capture unprocessed exceptions on a specific page, we need to define an error event handler, as shown below:
protected void Page_Error(object sender, EventArgs e)
{
Exception ex = server.GetLastError();
if(ex is NotImplementedException)
Server.Transfer("/errorpages/notimplementexception.aspx");
else
Server.Transfer("/errorpages/apperror.aspx");
Server.ClearError();
}
Through the getlasterror method of the server object, we can obtain the thrown exception. If the control is transmitted through server. Transfer, the exception information is retained. You can call getlasterror on the error page to display more detailed information. Finally, once all Exception Handling is completed, clearerror should be called to clear the error.
When displaying error messages, be sure not to expose sensitive information to prevent malicious users from using them to launch attacks on the system. We can make the page more flexible, so that it can determine whether the user is located locally, whether to use custom headers, and display detailed information helpful for error diagnosis:
if(Request.UserHostAddress == "127.0.0.1")
{
......
}
You can use the request. headers set to check custom header information. To add a custom header, enter the properties of the application Internet Information Service (IIS) virtual directory, and click the HTTP header tab.
Global error handling
Add the global. asax file to the program and write the code in the predefined application_error method:
void Application_Error(object sender, EventArgs e)
{
......
}
We can do something meaningful in this event handler, such as sending an email to the administrator or writing Windows event logs.
Error and page ing
When an unhandled exception arrives at the end of the call stack, ASP. NET generates a default page that displays a yellow screen. Through the <customerrors> section in the Application Web. config file, developers can fully customize the ASP. NET function:
<configuration>
<system.web>
......
<customErrors mode="RemoteOnly" defaultRedirect="/GerericError.aspx" />
</system.web>
</configuration>
No matter what the error is, ASP. NET redirects the user to the genericerror. ASPX page.
In addition to redirecting users to common error pages, ASP. NET also enables us to display custom pages for different HTTP errors, as shown in the following example:
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="/GenericError.aspx">
<error statusCode="404" redirect="/ErrorPages/Error404.aspx" />
<error statusCode="500" redirect="/ErrorPages/Error500.aspx" />
</customErrors>
</system.web>
</configuration>
When the underlying ASP. NET call error page, the URL of the page that causes the error will be passed in, for example:
public partial class Error404 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
object o = Request.QueryString["AspxErrorPath"];
if(o != null)
{
......
}
}
}
If the application-level error handling program, page-level processing program, and various redirection exist at the same time, which one will be given priority? Application-level processors take precedence over other processors. Page-level code runs after all code processes the internal HTTP 500 error.
ASP. NET tracking
. Net has a rich set of program tracking tools. In particular, trace and debug classes defined in the systems. Diagnostics namespace. These two classes are basically the same, both of which are based on the "listener" module. As a driver, listeners collect tracing messages and store these messages in specific media.
How to enable page Tracing
You can switch the trace attribute Switch Status in the web. config file of the application:
<configuration>
<system.web>
<trace enabled="true" pageOutput="true" />
</system.web>
</configuration>
The pageoutput attribute is used to indicate whether to display the output on the page. If pageoutput is set to false, the trace output is automatically sent to the trace. axd tool of ASP. NET.
The default trace attribute in the @ page command is false. If it is true, the trace information is displayed at the bottom of the page.
The @ page command also provides the tracemode attribute so that we can select the sorting method of the displayed data. The possible values are sotrbycategory and sortbytime. The default value is sortbytime.
The page class provides two attributes, tracemodevalue and traceenabled, which correspond to the preceding @ page command attributes respectively.
The third attribute related to the trace in the page class is trace, which returns an instance of the tracecontext class. You can append trace logs to the ASP. NET page by using the tracecontext class method. When an HTTP request is created, an instance of this type is created. The trace object is exposed through the trace attribute of the httpcontext class.
The isenabled attribute of the tracecontext class indicates whether the trace is enabled, and the tracemode attribute indicates the arrangement mode of the trace records on the page.
The write and warn methods of the tracecontext class output messages. The two methods are basically the same. The only difference is that the output messages of warn are red.
The text transmitted using the write and warn methods is displayed on the HTML page, but the HTML format label is not processed. This text is written in plain text. To obtain bold characters, add <B> and </B> to the substring of the tracing message.
If the external class sends text to the tracking log of the current HTTP request, it can be expressed as follows:
System. Web. httpcontext. Current. Trace. Write (category, MSG );
Once the application tracing function is enabled, each page request transfers the tracing information of a specific page to the viewer. We can request trace. axd in the application root directory to open the trace Viewer (for example, http: // localhost: 1105/core35/trace. axd ).
The number of requests that the trail viewer can cache is limited by the requestlimit attribute (default value: 10 ). Example:
<system.web>
<trace enable="true" requestList="20" />
</system.web>
The trace viewer automatically tracks all requests and caches the complete trace information for each request. When the number of requests reaches the upper limit, other requests will not be cached unless the current trace information is manually deleted.