There are three aspects of exception handling in ASP.NET:
Tracing - Tracing program execution at the page level or application level.
Error handling - Handle standard or custom errors at the page or application level.
Debugging - Advance through the program and set breakpoints to analyze the code.
In this chapter, we will discuss tracing and handling. And in this chapter, we'll cover debugging.
To understand the concepts, create the following sample application. It has a label control, a dropdown list and a link. The dropdown list loads an array of quotes and the selected quote will be displayed in the label below. It also has a hyperlink that points to a link that doesn't exist.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="errorhandling._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional// EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Tracing, debugging and error handling </title> </head> <body> <form id= "form1" runat="server"> <div> <asp:Label ID="lblheading" runat="server" Text="Tracing, Debuggin and Error Handling"> </asp:Label> <br /> <br / > <asp:DropDownList ID="ddlquotes" runat="server" AutoPostBack="True" onselectedindexchanged="ddlquotes_SelectedIndexChanged"> </asp:DropDownList> <br /> <br /> <asp:Label ID="lblquotes" runat= "server"> </asp:Label> <br /> <br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="mylink.htm">Link to:</asp:HyperLink> </div> </form> </body></html>
Code after file:
public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string[,] quotes = { {"Imagination is more important than Knowledge.", "Albert Einsten"}, {"Assume a virtue, if you have it not" "Shakespeare"}, {"A man cannot be comfortable without his own approval", "Mark Twain"}, {"Beware the young doctor and the old barber", "Benjamin Franklin"}, {"Whatever begun in anger ends in shame", "Benjamin Franklin"} }; for (int i=0; i<quotes.GetLength(0 ); i++) ddlquotes.Items.Add(new ListItem(quotes[i,0], quotes[i,1])); } } protected void ddlquotes_SelectedIndexChanged(object sender, EventArgs e) { if (ddlquotes.SelectedIndex != -1) { lblquotes.Text = String.Format("{0}, Quote: {1}", ddlquotes.SelectedItem.Text, ddlquotes.SelectedValue) ; } }}
To allow page-level tracing, you need to modify the Page directive and add a Trace attribute as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="errorhandling._Default" Trace ="true" %>
Now when you execute the file, you will get trace information:
It provides the following information in the header:
Session ID
Status Code
Time of Request
Type of Request
Request and Response Encoding
Each time the page is requested, the status code sent from the server displays the name and error time, if any. The following table shows common HTTP status codes:
number | describe |
---|---|
Notification(100 - 199) | |
100 | continue |
101 | conversion agreement |
Success(200 - 299) | |
200 | OK |
204 | No content |
Redirect (300 - 399) | |
301 | move permanently |
305 | Use a proxy |
307 | temporary redirect |
Errors from client (400 - 499) | |
400 | Bad request |
402 | Payment requirements |
404 | not found |
408 | Request timeout |
417 | Expect to fail |
Error from server (500 - 599) | |
500 | Internal Server Error |
503 | Service unavailable |
505 | HTTP version not supported |
Under the top-level information, there is a Trace log, which provides details of the page life cycle. It provides the elapsed time in seconds since the page was initialized.
The next section is the control tree, which lists all the controls on the page in a hierarchical format:
The last declaration in Session and Application is the summaries, cookies and headers collection followed by all server variables.
Trace objects allow you to add custom information to trace output. It has two methods to complete: Write method and Warn method.
Change the Page_Load event handler to detect the Write method:
protected void Page_Load(object sender, EventArgs e){ Trace.Write("Page Load"); if (!IsPostBack) { Trace.Write("Not Post Back, Page Load"); string[,] quotes = ... ............. }}
Run to see the impact:
To detect the Warn method, let's force some error code into the selected index changed event handler:
try{ int a = 0; int b = 9 / a;}catch (Exception e){ Trace.Warn("UserAction", "processing 9/a", e);}
Try-Catch is a C# programming construct. The try block holds any code that may or may not generate an error, and the catch block captures the error. When the program runs, it sends warnings in the trace log.
Application-level tracking applies to all pages in the website. It is implemented by placing the following code in the web.config file:
<system.web> <trace enabled="true" /></system.web>
Although ASP.NET detects all run-time errors, there are still some tiny errors that are still there. Observing errors through tracing is for developers, not users.
Therefore, to prevent this from happening, you can add error resolution settings in your application's web.config. It is application-wide error resolution. For example, you can add the following code to the web.config file:
<configuration> <system.web> <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound .htm" /> </customErrors> </system.web><configuration>
Some of the possible attributes: - **Mode:** It allows or disallows custom error pages. It has three possible values: - **On:** Display a custom page. - **Off:** Shows ASP.NET error page (yellow page) - **remoteOnly:** It shows custom errors to the client, showing local ASP.NET errors. - **defaultRedirect:** It contains the URL of the page to display in case of unresolved errors. In order to place different custom error pages for different error types, subtags are used, where different error pages are specified based on the status code of the error. In order to achieve page-level error resolution, the Page directive can be modified to: `````` Because ASP.NET Debugging is an important topic within it, we will discuss it separately in the next chapter.