一般异常处理,需要在程序中不断的try catch,不断的{}然后不断的调用,可能偶自己比较懒,想找个方便一点的方法,下面就是捕获页面最后一个异常并处理异常的例子:具体做法是,单独一个类,
比如我们叫他PageBase.cs
代码如:
- 1using System;
- 2
- 3namespace netw
- 4{
- 5 /** <summary>
- 6 /// PageBase 的摘要说明。
- 7 /// </summary>
- 8 public class PageBase:System.Web.UI.Page
- 9 {
- 10 protected void PageBase_Error(object sender, System.EventArgs e)
- 11 {
- 12 string errMsg;
- 13 //得到系统上一个异常
- 14 Exception currentError = Server.GetLastError();
- 15
- 16 errMsg= "<h1>页面错误</h1><hr/>此页面发现一个意外错误,对此我们非常抱歉。"+
- 17 "此错误消息已发送给系统管理员,请及时联系我们,我们会及时解决此问题! <br/>" +
- 18 "错误发生位置: "+Request.Url.ToString()+"<br/>"+
- 19 "错误消息: <font class=\"ErrorMessage\">"+ currentError.Message.ToString() + "</font><hr/>"+
- 20 "<b>Stack Trace:</b><br/>"+
- 21 currentError.ToString();
- 22
- 23 Session["err"]=errMsg;
- 24 //如果发生致命应用程序错误
- 25 if ( !(currentError is ApplicationException) )
- 26 {
- 27 //向Windows事件日志中写入错误日志
- 28 //LogEvent( currentError.ToString(), EventLogEntryType.Error );
- 29 }
- 30 //在页面中显示错误31 //Response.Write( errMsg );
- 32 Response.Redirect("error.aspx");
- 33 //清除异常
- 34 Server.ClearError();
- 35 }
- 36
- 37
- 38 private void PageBase_Load(object sender, System.EventArgs e)
- 39 {
- 40
- 41 }
- 42 protected override void OnInit(EventArgs e)
- 43 {
- 44 base.OnInit(e);
- 45 this.Error += new System.EventHandler(this.PageBase_Error);
- 46 }
- 47
- 48 }
这里是把出现异常的地址和具体信息发送到Response.Redirect("error.aspx"); 而error.aspx呢,我是把错误信息发送到自己信箱的,以便及时修正,没想到平均没天我信箱里就要收到200多封错误报告,清一色的数据库路径不对,
代码如:需要引入using System.Web.Mail;空间
- 1private void Page_Load(object sender, System.EventArgs e)
- 2 {
- 3 sendemadil();
- 4 Label1.Text=Session["err"].ToString();
- 5 }
- 6 private void sendemadil()
- 7 {
- 8 MailMessage msg = new MailMessage();
- 9 //发送方地址(如test@163.com)
- 10 msg.From ="madyina@163.com";
- 11 //接收方地址(如test@163.com)
- 12 msg.To =ConfigurationSettings.AppSettings["themail"];
- 13 //正文内容类型14 msg.BodyFormat = MailFormat.Html;
- 15 //正文内容编码
- 16 msg.BodyEncoding = System.Text.Encoding.Default;
- 17 //主题
- 18 msg.Subject ="网站错误报告";
- 19 //内容
- 20 msg.Body =Session["err"].ToString();
- 21
- 22 //设置为需要用户验证
- 23 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1" );
- 24 //设置验证用户名
- 25 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "你的信箱用户名");//用于验证的,不是接收的
- 26 //设置验证密码
- 27 msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "你的信箱密码");
- 28
- 29 //邮件服务器地址(如smtp.163.com)
- 30 SmtpMail.SmtpServer = "smtp.163.com";
- 31
- 32 //发送
- 33 SmtpMail.Send(msg);
- 34 }
- 35
- 36
需要处理异常的页面只需继承下这个类就可以了
继承示例:public class index ageBase 在需要的页面。