ASP.NET錯誤處理一般有三種處理方式:
1 在頁面級錯誤事件中,在單獨頁面中的錯誤。可以在page_error事件中添加處理邏輯,具體如下:
Private Sub Page_Error()Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error
Dim err As String = "Error in:" & Request.Url.ToString & "</p>" _
& "Stack Trace Below:</br>" _
& Server.GetLastError.ToString
Response.Write(err)
Server.ClearError()
End Sub
2 在應用程式級的錯誤事件中,在應用程式中的錯誤。可以在global.asax檔案中的application_error中添加處理 邏輯,具體如下:
Sub Application_Error()Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' 在發生錯誤時激發
Dim err As String = "<h1>Application Error</h1>" _
& "Error in:" _
& Request.Url.ToString & "</p>" _
& "Stack Trace Below:</br>" _
& Server.GetLastError.ToString
Response.Write(err)
Server.ClearError()
End Sub
3 在應用程式設定檔中,為應用程式執行的聲明性錯誤處理,具體如下:
<system.web>
<customErrors defaultRedirect="url" mode="RemoteOnly">
<error statusCode="code" redirect="url"></error>
</customErrors>
</system.web>
當頁面發生錯誤時,應用程式也應該讓管理員或開發人員知道何時何地出現了錯誤,一般有兩種方法。
1 向Event Log 寫入事件
Imports System.Diagnostics
Sub Application_Error()Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' 在發生錯誤時激發
Dim PageUrl As String = Request.Path
Dim ErrorInfo As Exception = Server.GetLastError()
Dim Message As String = "Url:" & PageUrl & "</br>"
Message = Message & " Error: "
Message = Message & ErrorInfo.ToString & "</br>"
Dim LogName As String = "MyCustomLog"
If (Not EventLog.SourceExists(LogName)) Then
EventLog.CreateEventSource(LogName, LogName)
End If
Dim Log As New EventLog
Log.Source = LogName
Log.WriteEntry(Message, EventLogEntryType.Error)
End Sub
2 發送Email
Sub Application_Error()Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' 在發生錯誤時激發
Dim PageUrl As String = Request.Path
Dim ErrorInfo As Exception = Server.GetLastError()
Dim Message As String = "Url:" & PageUrl & "</br>"
Message = Message & " Error: "
Message = Message & ErrorInfo.ToString & "</br>"
Dim Mymessage As New MailMessage
Mymessage.To = "tianhao960@gmail.com"
Mymessage.From = "tianhao960@gmail.com"
Mymessage.Subject = "ASP.NET Error"
Mymessage.BodyFormat = MailFormat.Text
Mymessage.Body = Message
SmtpMail.Send(Mymessage)
End Sub