Showing posts with label Handling Errors. Show all posts
Showing posts with label Handling Errors. Show all posts

Tuesday, January 6, 2009

Tracing in .Net

Tracing

We use tracing to pinpoint the problems in the code.Tracing allows to get whole host information about the currently executing request and write it in the trace of the page or in the Trace log.

Tracing can be achieved in two different methods.

-Page Level Tracing
-Application Level tracing

We can also dynamically turn Page level tracing on.
To enable page level tracing for the page we need to set the trace attribute to true in the
@page directive and then use trace.write () or Trace.warn() statements to write trace information to trace output.

Trace Context : Trace context is the class where .net stores information about all http requests and trace information. We can access Trace context class by using Page.trace attribute of the page .

Trace context class has 2 methods to write trace output to the page .They are

Trace.Write( )
Trace.Warn( )


The only difference between them is for Trace.Warn the output is ddisplayed in red in color such that it can be easily notified in the Trace log.

Both methods we have 3 versions .

1. If we pass single argument .Net writes it to Message column of the log file
2. If we use two string arguments, the first string appears in the Category column and the second in the Message column
3. If you use a third argument, it must be of type Exception and contain information about an error, which ASP.NET then writes to the trace log.

Trace.Write(“Page Loaded”)



The Trace Information section of 4 sections.

Category :
A custom trace category that you
specified as the first argument in a Trace.Write (or Trace.Warn) method call. Message :

A custom trace message that you specified as the second argument in a Trace.Write (or Trace.Warn) method call.
From First (s) :
The time, in seconds, since the request processing was started (a running total).
From Last (s) :
The time, in seconds,
since the last message was displayed. This column is especially helpful for seeing how long individual operations are taking.


Application Level Tracing:
If we don’t want to change paging in each and every page and we need to write the trace to entire application we opt for application level tracing.
To accomplish this we need to enable application-level tracing in the web.config file of the application and view the AXD application trace log for trace information.

Enable Application level tracing.
-To enable application tracing ,locate the web.config file in the application
-Add the trace element to System.web section of Web.config file and set the enabled attribute to true

‘<>

‘ <>


web.config:





<configuration>

<system.web>

<httpHandlers>

<remove verb="*" path="trace.axd" />

</httpHandlers>

</system.web>

</configuration>









-View the application trace log by browsing to the trace.axd page from the application root, like this:
http://localhost//trace.axd
trace.axd is not an page but rather it is a special URL that is intercepted by ASP.NET.
It is an http handler.

Some of the trace Elements are
RequestLimit: Defualt number of Http requests stored in the trace information are 10, if limit is reached tracing will be disabled,requests count can be set using this attribute.
pageOutput :If, in addition to viewing the trace.axd file,
you also want to see trace information displayed at the bottom of the page that it is associated with, add pageOutput="true" to the element:

The trace information you will see is identical to what would appear had you placed Trace="true" in the @ Page directive for the page
localOnly :To show trace information
to the local user (i.e., the browser making the request is on the machine serving the request) but not to remote users, make sure the element includes localOnly="true":


If we want to identify problems only
when an exception occurs.we can enable trace dynamically in the catch block.
· Set Page.Trace.IsEnabled = true in the Catch block of your exception handler.
· Write to the trace log by using a Trace.Write of the form Trace.Write("Exception", "Message", exc).












Error Handing in .Net FAQ

1. How to prevent errors at design time?

VB.Net offers the Option Strict and Option Explicit statements to prevent errors at design time.

• Option Explicit :

Prevent errors at design time. It forces explicit declaration of all variables at the module level

Syntax Option

Option Explicit On.

By default it is off.

We can set option explicit in .aspx page in the page directive




• Option strict :

Enabling Option Strict causes errors to be raised if you attempt a data type conversion that leads to a loss in data.


2.What Precisely is an Exception?

The Exception Class is a member of System NameSpace and base class for all the exceptions.

2 subclasses of Exception class are System Exception Class and Application Exception class.

Exception Class
System Exception Application Exception

The SystemException class defines the base class for all .NET predefined exceptions

3.What are the properties of Exception Object ?

Source : Gets the naem of the application or the object that causes the error
Message :Gets a message that describes the current exception.
StackTrace : Gets a string representation of the frames on the call stack at the time the current exception was thrown.
InnerException : Gets the Exception instance that caused the current exception
TargetSite : Gets the method that throws the current exception.
HelpLink :Gets or sets a link to the help file associated with this exception.

4.What is Structured and UnStructured Error Handling?

Unstructured Error Handling:


Unstructured error handling is implemented with the On Error statement, which is placed at the beginning of a code block to handle all possible exceptions that occur during the execution of the code. All Visual Basic 6.0 error handlers in .NET are objects that can be accessed by using the Microsoft.VisualBasic.Information.Err namespace. The handler is set to Nothing each time the procedure is called. You should place only one On Error statement in each procedure, because additional statements disable all previous handlers that are defined in that procedure.

On Error { GoTo [ line 0 -1 ] Resume Next }

Structured Error Handling :

With structured error handling, Visual Basic now has an effective way to prevent unexpected errors from terminating the execution of the application. Structured error handling also provides the programmers with a simpler way to create robust applications that are easier to maintain. Structured error handling is implemented in Visual Basic. NET or Visual Basic 2005 with a Try...Catch...Finally block of statements. The Try...Catch...Finally block provides, for the first time to Visual Basic, the capability of nested error handling.

5. Mention Predefined exceptions provided by .net run time?


Exception --Object--Base class for all exceptions.
SystemException--Exception--Base class for all runtime-generated errors.
IndexOutOfRangeException--SystemException--Thrown by the runtime only when an array indexed improperly.
NullReferenceException--SystemException--Thrown by the runtime only when a null object
referenced.

InvalidOperationException--SystemException--Thrown by methods when in an invalid state.

ArgumentException --SystemException--Base class for all argument exceptions.

ArgumentNullException --ArgumentException--Thrown by methods that do not allow
an argument to be null.
ArgumentOutOfRangeException --ArgumentException --Thrown by methods that verify
that arguments are in a given range.

ExternalException--SystemException--Base class for exceptions that occur or are targeted
at environments outside the runtime.

ComException--ExternalException--Exception encapsulating COM HRESULT information.

SEHException --ExternalException--Exception encapsulating Win32 structured exception handling information

6.What class we need to inherit to create custom Excepton class.
To create a custom exception we must inherit from the ApplicationException class

7.How to redirect the user to the friendly error-handler page when an Application error occurs?

Modify web.config as


customErrors mode="On" defaultRedirect="errorpage.aspx"

The configuration section supports an inner tag that associates HTTP status codes with custom error pages. For example:

--< mode="On" defaultredirect="genericerror.htm">
-- < statuscode="404" redirect="pagenotfound.aspx">
--< statuscode="403" redirect="noaccess.aspx">
--< /customerrors>







Error Handling in asp.net


The Error handling model in asp.net lets you handle errors at 3 different levels

Method Level
Page Level
Application Level


Method Level:

We use Method level error handling for all the recoverable errors.
For non recoverable errors it goes to next level.

For the all the errors which can be handled we use

Try…Catch blocks

For throwing any message if an error occurred or any exception we use .

Throw… block

To clean up the error we use

Finally… block


Syntax:

Try

‘’..code for execution

Catch ex as Exception

‘’..handle the error

Finally

‘clear the error

End try



Try block contains the code need to be implemented ,
Catch block is used to handle the error
Finally block used to clear the error.


Let us suppose we are using database connection in the code and if the error occurs in the query .net framework doesn’t close the database connections. I this case we need to write the code in the FINALLY block to close he connection.


Page Level:

We use Page Level event handling when we want to trap the errors occurred in the page and redirect the user to another page which the displays the error details.

Implementation:

Write required code in the Page_Error event handler of the page.

The Page_Error event of the ASP.NET Page object is raised any time an unhandled error occurs in a page


Use GetLastError method to get reference to the latest error occurred


Set the ErrorPage property of the page object to the URL of the page which need to display the error details

The page will be redirected to the url mentioned when any unhandled error occurs.


Add error number,message to the query string in the URL.
Dim lastError As Exception

'get the last error that occurred

lastError = Server.GetLastError( )
Page.ErrorPage = "Errorpage.aspx"?errMessage=" & lastError.Message &errnumber=" & lastError.number

  • When any Unhandled error occurred in the page level ,Page_Error event is triggered and the page will be redirected to the error page mentioned with all the details of the error in the query string.
  • If we don’t add any Query string parameters,.NET will assign one for usi.e aspxerrorpath which gives relative path of the error message.

Application Level: If we want to Log all the errors raised in an application in Single location we use application level error handling. Add Page_Error event handler to the page to throw the error to next level i.e application level Add Application_error event handler in global.asax file to perform logging and redirection
To process errors at the application level, each page must include the Page_Error event handler with a single line of code to rethrow the last exception that occurred.

Private Sub Page_Error(ByVal sender As ObjectByVal e As System.EventArgs) Handles MyBase.Error 'Rethrow the last error that occurred

Throw Server.GetLastError( )

End Sub

***********Error handling in Application_error

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

Const EVENT_LOG_NAME As String = "Application"

Dim lastException As Exception

Dim Log As EventLog

Dim message As String

'get the last error that occurred

lastException = Server.GetLastError( )

'create the error message from the message in the last exception along 'with a complete dump of all of the inner exceptions (all exception 'data in the linked list of exceptions)

message = lastException.Message & lastException.ToString( )

'Insert error information into the event log

Log = New EventLog

Log.Source = EVENT_LOG_NAME

Log.WriteEntry(message,EventLogEntryType.Error)

'perform other notifications, etc. here

'clear the error and redirect to the page used to display the 'error information

Server.ClearError( )

Response.Redirect("Errorpage.aspx?errMessage=" & lastException.Message _)

End Sub