您的位置:首页 > 编程语言 > ASP

ASP.NET错误处理

2007-03-20 11:16 363 查看

ASP.NET错误处理

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: