异常处理注意事项
• 当引发异常时,要提供有意义的文本。
• 要引发异常仅当条件是真正异常;也就是当一个正常的返回值不满足时。
• 如果你的方法或属性被传递一个坏参数,要引发一个ArgumentException异常。
• 当调用操作不适合对象的当前状态时,要引发一个InvalidOperationException异常。
• 要引发最适合的异常。
• 要使用链接异常,它们允许你跟踪异常树。
• 不要为正常或预期的错误使用异常。
• 不要为流程的正常控制使用异常。
• 不要在方法中引发NullReferenceException或IndexOutOfRangeException异常。
异常处理技术
• 记录异常
–在文件中记录异常
–在数据库中记录异常
–在eventlog中记录异常
• 发送email通知异常
• 异常产生时,用友好(user-friendly)的方式通知用户
处理错误
• Page_Error事件
• Application_Error事件
• 利用配置文件,自定义错误页面
– <customErrors defaultRedirect="url" mo
de="RemoteOnly">
<error statusCode="code" redirect="url
"></error>
</customErrors>
编写到windows错误日志
//
窗体的error事件
private void WebForm1_Error( object sender, System.EventArgs e)
... {
string strMessage = Server.GetLastError().Message;
//Response.Write(strMessage);
Server.ClearError();
//以下把信息写入windows日志
//要把aspnet用户添加到管理员组中,以便有写注册表权限
if(!EventLog.SourceExists("mySource"))
EventLog.CreateEventSource("mySource","myLog");
EventLog Event = new EventLog();
Event.Source = "mySource";
Event.WriteEntry(strMessage,EventLogEntryType.Warning);
//EventLog.Delete("myLog");
throw new Exception("我处理不了,请最高人民法院处理!");
}
private void WebForm1_Error( object sender, System.EventArgs e)
... {
string strMessage = Server.GetLastError().Message;
//Response.Write(strMessage);
Server.ClearError();
//以下把信息写入windows日志
//要把aspnet用户添加到管理员组中,以便有写注册表权限
if(!EventLog.SourceExists("mySource"))
EventLog.CreateEventSource("mySource","myLog");
EventLog Event = new EventLog();
Event.Source = "mySource";
Event.WriteEntry(strMessage,EventLogEntryType.Warning);
//EventLog.Delete("myLog");
throw new Exception("我处理不了,请最高人民法院处理!");
}
把错误发送邮件到管理员
//
在Global.asax.cs中写
protected void Application_Error(Object sender, EventArgs e)
... {
//把错误信息发送到作者
string strPageUrl = Request.Path;
Exception ErrorInfo =Server.GetLastError();
//Server.ClearError();
string strMessage = "Url:" + strPageUrl + "</br>";
strMessage = strMessage + " Error: ";
strMessage = strMessage + ErrorInfo.ToString() + "</br>";
MailMessage Mymessage = new MailMessage();
Mymessage.To = "shaozhd@263.net";
Mymessage.From = "shaozhd@263.net";
Mymessage.Subject = "ASP.NET Error";
Mymessage.BodyFormat = MailFormat.Text;
Mymessage.Body = strMessage;
SmtpMail.Send(Mymessage);
}
protected void Application_Error(Object sender, EventArgs e)
... {
//把错误信息发送到作者
string strPageUrl = Request.Path;
Exception ErrorInfo =Server.GetLastError();
//Server.ClearError();
string strMessage = "Url:" + strPageUrl + "</br>";
strMessage = strMessage + " Error: ";
strMessage = strMessage + ErrorInfo.ToString() + "</br>";
MailMessage Mymessage = new MailMessage();
Mymessage.To = "shaozhd@263.net";
Mymessage.From = "shaozhd@263.net";
Mymessage.Subject = "ASP.NET Error";
Mymessage.BodyFormat = MailFormat.Text;
Mymessage.Body = strMessage;
SmtpMail.Send(Mymessage);
}