六、跟踪错误信息
当前页面没有余留跟踪信息,可设置当前页
<%@Page Language=”C#” Trace=”true”%>
在程序中添加跟踪代码:
for (int i = 0; i < 10; i++)
{
Response.Write(i);
Trace.Warn("第一:",i.ToString()); 卡杜巴
}
Web应用程序的所有页面均显示跟踪信息
发布时应把pageOutput=”false”;
如果不到客户那去排除错误时用
在Web.config中设置
<system.web>
<trace enabled="true" pageOutput="false"/>
</system.web>
然后在地址栏输入
http://localhost:44158/WebSite1/trace.axd
七、Page_Error实现当前页面级的错误处理 http://www.chinakdb.com/
protected void Button1_Click(object sender, EventArgs e)
{
//模拟能够预料的错误 卡杜巴
int n;
bool txt = int.TryParse(TextBox1.Text,out n);
if (txt)
{
Label1.Text = "显示:" + txt;
}
else
{
Label1.Text = "输入的不是数字";
}
}
//多个按钮事件的错误处理
protected void Button2_Click(object sender, EventArgs e)
{
//模拟不可预料的错误
int n = Convert.ToInt32(TextBox1.Text);
}
protected void Button3_Click(object sender, EventArgs e)
{
int n = Convert.ToInt32(TextBox1.Text);
}
//Page_Error实现当前页面级的错误处理:收集页面上所有的错误信息
protected void Page_Error(object o, EventArgs e)
{
//把服务端的错误信息转到单独的页面上
Server.Transfer("~/错误页面.aspx");
}
//错误页面代码
public partial class 错误页面 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Server.GetLastError:获得异常并处理
Exception ex = Server.GetLastError();
//显示错误信息
Label1.Text = ex.Message;
//处理完清除(提高性能)
Server.ClearError();
}
}
八、全局错误处理:收集所有的页面 http://www.chinakdb.com/
在一个按钮事件为程序序判断错误
1、在项目中添加全局应用程序类,后缀名按默认
2、在Gloab文件中Application_Error方法下添加代码,代码如下
void Application_Error(object sender, EventArgs e)
{
//在出现未处理的错误时运行的代码
//有错误,须跳转到特定错误页面 卡杜巴
Server.Transfer("~/错误页面.aspx");
}
3、在错误页面Page_Load事件中添加代码如下
Exception ex = Server.GetLastError();
Label1.Text = ex.Message;
Server.ClearError();
九、使用定制页面错误 http://www.chinakdb.com/
1、 如果不需要处理错误的详细信息,可以通过配置文件配置指定错误处理页面
2、 当一个未处理的异常达到调用栈的根时,则显示指定的错误页面更友好更专业
3、 定制错误页往往是普通的HTML页面,保证不会递归的引发错误
在项目根目录下添加HTMl页面
HTMl页面中:如果程序有错误 就跳转到此页面
例:显示:Sorry!
在Web.config配置文件中代码如下:
l 在<authentication mode="Windows" />下添加代码
<!--开发中customErrors mode应设为Off-->
<customErrors mode="On" defaultRedirect="HTMLPage.htm" >
</customErrors>
本文介绍ASP.NET中的多种错误处理方式,包括跟踪错误信息、Page_Error实现当前页面级的错误处理、全局错误处理以及使用定制页面错误等。通过这些方法可以有效地管理和解决Web应用中的异常情况。
1992

被折叠的 条评论
为什么被折叠?



