星期五, 9月 02, 2005

在asp.net中處理意外情況

於Global.asax 中的 Application_Error 事件加上以下的內容 , 如此
當系統發生意外情況時 , 則會將錯誤訊息 mail 給指定的人 , 並將網頁導至
Maintenance.aspx

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' 發生錯誤時引發
If (System.Web.HttpContext.Current.Request.Url.Authority <> "localhost") Then
''' Get the Exception object wrapped in the InnerException property
Dim unhandledException As Exception = Server.GetLastError().InnerException
''' Create a MailMessage
Dim mail As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage
mail.From = "error@abc.com"
mail.To = "admin@abc.com"
mail.BodyFormat = System.Web.Mail.MailFormat.Text
mail.Subject = "unHandledException.Message"
mail.Body = unhandledException.ToString()
System.Web.Mail.SmtpMail.SmtpServer = "127.0.0.1"
''' Send the email
System.Web.Mail.SmtpMail.Send(mail)
''' Redirect the user to a maintenence page
System.Web.HttpContext.Current.Response.Redirect("Maintenance.aspx")
End If
End Sub