ASP.NET - 错误处理

ASP.NET中的错误处理有三个方面:

  • 跟踪  - 跟踪程序在页面级别或应用程序级别执行.

  • 错误处理  - 在页面级别或应用程序级别处理标准错误或自定义错误.

  • 调试  - 单步执行程序,设置断点以分析代码

在本章中,我们将讨论跟踪和错误处理,在本章中,我们将讨论调试.

要理解这些概念,请创建以下示例应用程序.它有一个标签控件,一个下拉列表和一个链接.下拉列表加载着名引号的数组列表,所选引号显示在下面的标签中.它还有一个指向不存在的链接的超链接.

<%@ 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>


文件背后的代码:

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);
      }
   }
}


跟踪

启用页面级别跟踪,您需要修改Page指令并添加Trace属性,如下所示:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
   Inherits="errorhandling._Default" Trace ="true" %>


现在,当您执行该文件时,您将获得跟踪信息:

跟踪信息

它在顶部提供以下信息:

  • 会话ID

  • 状态代码

  • 请求时间

  • 请求类型

  • 请求和响应编码

每次请求页面时,从服务器发送的状态代码显示名称和错误的时间,如果有的话.下表显示了常见的HTTP状态代码:

数字描述
信息(100  -  199)
100继续
101切换协议
成功(200  -  299)
200确定
204无内容
重定向(300  -  399)
301
永久移动
305使用代理
307临时重定向
客户端错误(400  -  499)
400错误请求
402需要付款
404未找到
408请求超时
417期望失败
服务器错误(500  -  599)
500内部服务器错误
503服务不可用
505不支持HTTP版

在顶级信息下,有Trace log,它提供页面生命周期的详细信息.它提供了自页面初始化以来经过的秒数.

Tracing Info2

下一节是控制树,它以分层方式列出页面上的所有控件:

Tracing Info3

最后在会话和应用程序状态摘要,cookie和标题集合中,后跟所有服务器变量的列表.

跟踪object允许您将自定义信息添加到跟踪输出.它有两种方法可以实现:Write方法和Warn方法.

更改Page_Load事件处理程序以检查Write方法:

protected void Page_Load(object sender, EventArgs e)
{
   Trace.Write("Page Load");
   
   if (!IsPostBack)
   {
      Trace.Write("Not Post Back, Page Load");
      string[,] quotes = 
      .......................
   }
}


运行以观察效果:

跟踪Info4

要检查Warn方法,让我们在选定的索引更改事件处理程序中强行输入一些错误代码:

try
{
   int a = 0;
   int b = 9 / a;
}catch (Exception e)
{
   Trace.Warn("UserAction", "processing 9/a", e);
}


Try-Catch是一个C#编程结构. try块保存可能产生或不产生错误的任何代码,catch块捕获错误.当程序运行时,它会在跟踪日志中发送警告.

Tracing Info5

应用程序级别跟踪适用于网站中的所有页面.它是通过在web.config文件中放入以下代码行来实现的:

<system.web>
   <trace enabled="true" />
</system.web>


错误处理

虽然ASP.NET可以检测所有运行时错误,但仍然存在一些微妙的错误.通过跟踪来观察错误是针对开发人员而不是针对用户.

因此,要拦截此类事件,您可以在应用程序的web.config文件中添加错误处理设置.它是应用程序范围的错误处理.例如,您可以在web.config文件中添加以下行:

<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>


< customErrors> section具有可能的属性:

  • 模式:它启用或禁用自定义错误页面.它有三个可能的值:

    • 开启:显示自定义页面.

    • 关闭:显示ASP.NET错误页面(黄页)

    • remoteOnly :它向客户端显示自定义错误,在本地显示ASP.NET错误.

  • defaultRedirect :它包含在未处理错误的情况下显示的页面的URL.

要为不同类型的错误添加不同的自定义错误页面,&lt ;错误&GT;根据错误的状态代码,使用子标记,其中指定了不同的错误页面.

要实现页面级错误处理,可以修改Page指令:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
   Inherits="errorhandling._Default" Trace ="true" ErrorPage="PageError.htm" %>


因为ASP.NET调试本身就是一个重要的主题,所以我们将在下一章单独讨论它.