ASP.NET Error Handling and Tracing

ASP.NET Trace
ASP.NET introduces tracing functionality which allows one to view diagnostic information about a single request for an ASP.NET page simply by enabling it for your page or application.
Page Tracing Steps

Add trace directive at top of page
<%@ Page Trace=“True” %>

Add trace calls throughout page
Trace.Write(“Button Event Clicked”)
Trace.Warn(“Data Value: “ + checkValue)

Access page from browser

Trace Information generated :

Enabling Application-Level Tracing
To enable application level tracing add following line in Web.config :

<configuration>
<system.web>
<trace enabled=”true” localonly=”false” requestlimit=”40″>
</system.web>
</configuration>
 
Error Handling

All runtime errors is handled by exceptions.Exception would contain full stack information with error information.Exception handling is done using try/catch/finally/throw blocks and statements.

ASP.NET also provides declarative application custom error handling

  1. Enable programmatic logging of problems
  2. Automatically redirect users to error page when unhandled exceptions occur

Application_Error
Application_error is global applicaion event raised if unhandled exception occurs.This provides access to Current Request object. Also , provides access to Exception object. This enables developers to log and track errors.
One can use EventLog class to write custom logs in Application_Error event. Also one can use SmtpMail class to send mails to administrators.

NT Event Log

Dim LogName As String = “MyAppLog”
Sub Application_Start(Sender as Object, E as EventArgs)

If (Not EventLog.SourceExists(LogName)) Then

EventLog.CreateEventSource(LogName, LogName)

End if

End Sub

Sub Application_Error(Sender as Object, E as EventArgs)

Dim Message As String = “Url ” & Request.Path & ” Error: ” & Me.Error.ToString()

Dim Log as New EventLog

Log.Source = LogName

Log.WriteEntry(Message, EventLogEntryType.Error)

End Sub

Sending SMTP Mail

Sub Application_Error(Sender as Object, E as EventArgs)

Dim MyMessage as New MailMessage

MyMessage.To = “contactus@alltechnicalfaqs.com”

MyMessage.From = “MyAppServer”

MyMessage.Subject = “Unhandled Error”

MyMessage.BodyFormat = MailFormat.Html

MyMessage.Body = Request.Path  + Me.Error.ToString();

SmtpMail.Send(MyMessage)

End Sub

Leave a Reply